在Java中,緩衝字符(BufferedWriter )是一個字符流類來處理字符數據。不同於字節流(數據轉換成字節),你可以直接寫字符串,數組或字符數據保存到文件。
package com.yiibai.iofile; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteToFileExample { public static void main(String[] args) { try { String content = "This is the content to write into file"; File file = new File("/users/mkyong/filename.txt"); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } } }