將內容追加到文件尾部-採用字符流的形式,將abc.txt中的內容更換爲 好好學習,天天向上!

<span style="font-size:18px;">import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Writer;

//採用字符流的形式,將abc.txt中的內容更換爲  好好學習,天天向上!
public class Demo1 {
	public static void main(String[] args) {
		// fun1();
		appendMethodA("./res/abc.txt", "!");
	}

	/**
	 * 最原始的添加辦法
	 */
	private static void fun1() {
		File file = new File("./res/abc.txt");
		File file2 = new File("./res/ab.txt");
		try (Reader is = new FileReader(file);
				Writer os = new FileWriter(file2);) {
			char[] buffer = new char[4];
			int len = -1;
			while ((len = is.read(buffer)) != -1)
				os.write(buffer, 0, len);
			os.write('!');
			os.flush();
		} catch (Exception e) {

		}

		file.delete();
		file2.renameTo(new File("./res/abc.txt"));
	}

	/**
	 * 將內容追加到文件尾部A
	 * 
	 * @param fileName
	 * @param content
	 */
	public static void appendMethodA(String fileName, String content) {
		try {
			// 打開一個隨機訪問文件流,按讀寫方式
			RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
			// 文件長度,字節數
			long fileLength = randomFile.length();
			// 將寫文件指針移到文件尾。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content);
			randomFile.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 將內容追加到文件尾部B
	 * 
	 * @param fileName
	 * @param content
	 */
	public static void appendMethodB(String fileName, String content) {
		try {
			// 打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
			FileWriter writer = new FileWriter(fileName, true);
			writer.write(content);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
</span>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章