在 Java 開發中,文本文件的讀寫是基礎且高頻的操作。無論是配置文件解析、日誌記錄,還是數據導入導出,掌握高效、正確的 I/O 方式至關重要。本文系統梳理 Java 中處理文本文件的主流方案,涵蓋字節流與字符流、緩衝機制、追加寫入及資源管理最佳實踐,並附帶完整代碼示例,幫助開發者快速選型並避坑。
早期常用方式,適合簡單輸出,但需手動處理編碼轉換,現代開發較少直接使用。
import java.io.*;
public class WriteDemo1 {
public static void main(String[] args) {
FileOutputStream fos = null;
PrintStream ps = null;
try {
fos = new FileOutputStream("a.txt");
ps = new PrintStream(fos, true, "UTF-8"); // 指定編碼並啟用自動刷新
ps.println("qun qun.");
ps.println("fei fei");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 資源關閉建議使用 try-with-resources (JDK 7+)
if (ps != null) ps.close();
if (fos != null) {
try { fos.close(); } catch (IOException ignored) {}
}
}
}
}
面向字符操作,自動處理字符編碼,API 更友好(print/println/printf)。
import java.io.*;
public class WriteDemo2 {
public static void main(String[] args) {
// 使用 try-with-resources 自動關閉資源(推薦寫法)
try (FileWriter fw = new FileWriter("b.txt");
PrintWriter pw = new PrintWriter(fw)) {
pw.print("qunqun ");
pw.println("feifei ss");
pw.print("qunqun ");
} catch (IOException e) {
e.printStackTrace();
}
}
}
引入緩衝區減少磁盤 I/O 次數,顯著提升大量文本寫入性能。支持 newLine() 跨平台換行。
import java.io.*;
public class WriteDemo3 {
public static void main(String[] args) {
String content = "This is a simple example";
// 標準寫入(覆蓋模式)
try (FileWriter fw = new FileWriter("c.txt");
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(content);
bw.flush(); // 手動刷新確保數據落盤
} catch (IOException e) {
e.printStackTrace();
}
// 追加寫入模式:FileWriter 第二個參數傳 true
try (FileWriter fw = new FileWriter("c.txt", true);
BufferedWriter bw = new BufferedWriter(fw)) {
bw.newLine(); // 跨平台換行
bw.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
new FileWriter(path, true) 或 new FileOutputStream(path, true)。
早期 JDK 方案,readLine() 已棄用,且編碼處理麻煩,僅做歷史了解。
import java.io.*;
public class ReadDemo1 {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("a.txt");
DataInputStream dis = new DataInputStream(fis)) {
String line;
// available() 判斷非標準,建議改用 readLine() != null 邏輯
while ((line = dis.readLine()) != null) { // 實際開發請遷移至 BufferedReader
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
緩衝字符流,按行讀取效率高,自動處理字符解碼,是現代 Java 文本讀取的標準姿勢。
import java.io.*;
public class ReadDemo2 {
public static void main(String[] args) {
// JDK 7+ try-with-resources 確保資源釋放
try (FileReader fr = new FileReader("a.txt");
BufferedReader br = new BufferedReader(fr)) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
System.out.println(++count + " : " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
new FileWriter(path, StandardCharsets.UTF_8) (JDK 11+) 或 OutputStreamWriter 顯式指定 charset,避免跨平台亂碼。Files.lines(), Files.write()) 或 mmap 機制,避免 OOM。Path / Paths.get() (NIO.2) 處理跨平台路徑,而非字符串拼接。java.nio.file.Files API。import java.nio.file.*;
import java.util.List;
// 讀取所有行(自動關閉流,默認 UTF-8)
List lines = Files.readAllLines(Paths.get("a.txt"));
// 寫入列表(覆蓋模式,自動換行)
Files.write(Paths.get("b.txt"), lines, StandardCharsets.UTF_8);
// 追加寫入
Files.write(Paths.get("b.txt"), List.of("new line"), StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
掌握上述核心類與現代 API,即可從容應對 Java 文本文件讀寫的絕大多數業務場景。選對工具,事半功倍。