一,FileWritter寫入文件
FileWritter, 字符流寫入字符到文件。默認情況下,它會使用新的內容取代所有現有的內容,然而,當指定一個true (布爾)值作為FileWritter構造函數的第二個參數,它會保留現有的內容,并追加新內容在文件的末尾。
1. 替換所有現有的內容與新的內容。
new FileWriter(file);2. 保留現有的內容和附加在該文件的末尾的新內容。
追加文件示例
一個文本文件,命名為“javaio-appendfile.txt”,并包含以下內容。
ABC Hello追加新內容 new FileWriter(file,true)
結果
現在,文本文件“javaio-appendfile.txt”內容更新如下:
ABC Hello This content will append to the end of the file
二,BufferedWriter寫入文件
緩沖字符(BufferedWriter )是一個字符流類來處理字符數據。不同于字節流(數據轉換成字節),你可以直接寫字符串,數組或字符數據保存到文件。
三,FileOutputStream寫入文件
文件輸出流是一種用于處理原始二進制數據的字節流類。為了將數據寫入到文件中,必須將數據轉換為字節,并保存到文件。請參閱下面的完整的例子。
//更新的JDK7例如,使用新的“嘗試資源關閉”的方法來輕松處理文件。
package com.yiibai.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
File file = new File("c:/newfile.txt");
String content = "This is the text content";
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
新聞熱點
疑難解答