Java IO 按處理單位分為字節流(InputStream/OutputStream)與字符流(Reader/Writer);按功能分為節點流(直接操作目標)與處理流(包裝增強)。本文通過完整代碼示例,系統總結文件讀寫的四種核心模式並對比性能。
public static void readByBytes(String filename) {
try (FileInputStream in = new FileInputStream(filename)) {
int b;
while ((b = in.read()) != -1) { System.out.print((char)b); }
} catch (IOException e) { e.printStackTrace(); }
}
public static void readByBytesBuffer(String filename) {
try (FileInputStream in = new FileInputStream(filename)) {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) { System.out.write(buf, 0, len); }
} catch (IOException e) { e.printStackTrace(); }
}
public static void readByChars(String filename) {
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(filename), "UTF-8")) {
char[] buf = new char[1024];
int len;
while ((len = reader.read(buf)) != -1) { System.out.print(new String(buf, 0, len)); }
} catch (IOException e) { e.printStackTrace(); }
}
public static void readByLines(String filename) {
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) { System.out.println(line); }
} catch (IOException e) { e.printStackTrace(); }
}
public static void readRandomAccess(String filename) {
try (RandomAccessFile raf = new RandomAccessFile(filename, "r")) {
raf.seek(100); // 定位
byte[] buf = new byte[10];
raf.read(buf);
System.out.write(buf);
} catch (IOException e) { e.printStackTrace(); }
}
public static void writePerformanceTest() throws IOException {
String path = "E:/test/";
int times = 10000;
// 1. FileOutputStream 直接寫
long start = System.currentTimeMillis();
try (FileOutputStream fos = new FileOutputStream(path + "fos.txt")) {
for (int i = 0; i < times; i++) fos.write('a');
}
System.out.println("FileOutputStream: " + (System.currentTimeMillis() - start) + "ms");
// 2. BufferedWriter 緩衝寫入
start = System.currentTimeMillis();
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "bw.txt"), "UTF-8"))) {
for (int i = 0; i < times; i++) { bw.write('a'); bw.newLine(); }
}
System.out.println("BufferedWriter: " + (System.currentTimeMillis() - start) + "ms");
// 3. FileWriter 便捷寫入
start = System.currentTimeMillis();
try (FileWriter fw = new FileWriter(path + "fw.txt")) {
for (int i = 0; i < times; i++) fw.write('a');
}
System.out.println("FileWriter: " + (System.currentTimeMillis() - start) + "ms");
}
| 方式 | 適用場景 | 性能 | 推薦指數 |
|---|---|---|---|
| FileOutputStream | 二進制、圖片、視頻 | 基準 | ⭐⭐ |
| BufferedInputStream/Reader | 大文件文本讀取 | 提升 10-100 倍 | ⭐⭐⭐⭐⭐ |
| BufferedWriter | 大量文本寫入 | 顯著優於直接寫 | ⭐⭐⭐⭐⭐ |
| FileWriter | 簡單文本寫入 | 中等 | ⭐⭐⭐ |
| RandomAccessFile | 斷點續傳、大文件隨機讀寫 | 視場景 | ⭐⭐⭐ |
BufferedReader(文本)或 BufferedInputStream(二進制)。BufferedWriter 或 BufferedOutputStream。