在日常 Java 開發中,檔案讀寫是處理資料輸入輸出的核心技能。無論是讀取配置檔、處理日誌,還是處理二進位資料,掌握高效的 I/O 操作都至關重要。本文系統整理 Java 檔案讀寫的各種方式,並提供完整的程式碼範例供參考。
根據資料類型與讀取需求,Java 提供了四種主要的檔案讀取策略:
使用 FileInputStream 以位元組為單位讀取,適合圖片、音訊、視訊等二進位資料:
public static void readFileByBytes(String filename) {
File file = new File(filename);
try (FileInputStream in = new FileInputStream(file)) {
// 單位元組讀取
int temp;
while ((temp = in.read()) != -1) {
System.out.println(temp);
}
// 批次讀取(效率更高)
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
透過 InputStreamReader 將位元組轉換為字元,支援指定編碼(如 UTF-8),避免中文亂碼:
public static void readFileByChars(String filename) {
File file = new File(filename);
try (Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
char[] buffer = new char[1024];
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, charsRead));
}
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader 提供 readLine() 方法,是處理大型文字檔的首選:
public static void readFileByLines(String filename) {
File file = new File(filename);
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
int lineNum = 1;
while ((line = reader.readLine()) != null) {
System.out.println("Line " + lineNum++ + ": " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
支援任意位置跳轉讀寫,適合大檔案的斷點續傳或索引式存取:
public static void readFileRandomAccess(String filename) {
try (RandomAccessFile raf = new RandomAccessFile(filename, "r")) {
long fileLength = raf.length();
long startPos = fileLength > 4 ? 4 : 0;
raf.seek(startPos);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = raf.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
根據效能需求與資料類型選擇適當的寫入方式:
try (FileOutputStream fos = new FileOutputStream("output.dat")) {
fos.write("Hello World".getBytes("UTF-8"));
}
try (FileWriter fw = new FileWriter("output.txt")) {
fw.write("Hello World");
}
try (BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8"))) {
for (int i = 0; i < 1000; i++) {
bw.write("Line " + i);
bw.newLine(); // 跨平台換行
}
}
java.nio.file.Files 提供了更簡潔的 API:
// 一次性讀取所有行 Listlines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8); // 串流式處理大檔案(惰性載入) try (Stream stream = Files.lines(Paths.get("file.txt"))) { stream.filter(line -> line.contains("ERROR")) .forEach(System.out::println); } // 寫入檔案 Files.write(Paths.get("output.txt"), Collections.singletonList("Content"), StandardCharsets.UTF_8, StandardOpenOption.CREATE);
掌握這些檔案操作技巧,能顯著提升處理資料輸入輸出的效率與程式碼品質。建議根據實際業務場景選擇最適合的方式,並在程式碼中統一採用 try-with-resources 確保資源正確釋放。