檔案有 3 行,程式只輸出前 2 行。程式碼使用 `System.out.write(tem)` 逐位元組寫入標準輸出。
`System.out` 是 `PrintStream`,`write(int b)` 方法**不自動刷新**,資料留在內部緩衝區。`print/println` 遇到換行符 (`\n`) 會自動 `flush()`。檔案前兩行結尾有換行,故自動輸出;第三行結尾無換行 (或為 EOF),緩衝區未刷新,程式結束前未顯示。
while ((tem = in.read()) != -1) {
System.out.write(tem);
}
System.out.flush(); // ★ 迴圈結束後強制刷新,輸出剩餘緩衝資料
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) System.out.println(line);
}
Files.lines(Paths.get(file)).forEach(System.out::println);
try (InputStream in = new FileInputStream(file)) {
in.transferTo(System.out); // 直接管道傳輸,無緩衝問題
}
教訓:使用 `write(int)` 寫入 `PrintStream` 時,務必在結束時呼叫 `flush()`;實務上盡量用高層 API 避免手動位元組處理。