完整可執行程式碼
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
byte[] buffer = new byte[1024];
FileInputStream fis = null;
try {
fis = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
System.err.println("找不到檔案: " + args[0]);
System.exit(1);
}
try {
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
System.out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
System.err.println("讀取錯誤: " + e.getMessage());
} finally {
try {
if (fis != null) fis.close();
} catch (IOException e) {
System.err.println("關閉檔案失敗: " + e.getMessage());
}
}
}
}
關鍵技術點解析
- 緩衝區大小:1024 位元組(1KB)為常見折衷值,可根據檔案特性調整。
- 讀取迴圈條件:
read() 回傳實際讀取位元組數,-1 表示 EOF,比原文 boolean 旗標更標準。
- 資源釋放:使用
finally 區塊確保 close() 呼叫,避免檔案控制代洩漏(Java 7+ 建議改用 try-with-resources)。
- 錯誤輸出:錯誤訊息導向
System.err,區分於正常輸出。
進階替代方案
Files.readAllBytes(Path)(Java 7+):小檔案一次性讀入記憶體最簡潔。
BufferedInputStream 包裝 FileInputStream:大檔案序列讀取效能更佳。
Files.lines(Path):文字檔案逐行處理的現代 Stream API 寫法。