為什麼要學會用 FileWriter?
之前的student資料都只存在 記憶體 (RAM),程式一關就消失,FileWriter 可以把文字資料寫進檔案 (例如 .txt、.csv),達成 資料持久化 (Persistence)。
FileWriter 基本語法
import java.io.FileWriter;
import java.io.IOException;
public class Demo {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("output.txt");
fw.write("Hello, world!\n");
fw.write("This is written to a file.");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
特點
預設會 覆寫 (overwrite) 檔案內容。
如果要 追加 (append),要寫:
FileWriter fw = new FileWriter("output.txt", true);
總而言之實作結果:
確認存檔成功: