在 Java 程式設計中,讀取檔案內容並輸出到螢幕是一項基本技能。以下提供一個完整的範例程式,展示如何使用 FileInputStream 來讀取指定檔案,並將其內容原樣輸出至標準輸出裝置(螢幕)。
/* ReadFile.java
* 讀取檔案內容,並將原樣輸出至螢幕上
* 使用方法:java ReadFile 檔案名
*/
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
byte[] buffer = new byte[1024];
boolean continueReading = true;
FileInputStream inputStream = null;
// 建立 FileInputStream 物件準備讀取檔案
try {
inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
System.err.println("找不到檔案");
System.exit(1);
}
while (continueReading) {
try {
int bytesRead = inputStream.read(buffer); // 從檔案讀取資料
System.out.write(buffer, 0, bytesRead); // 寫入 System.out 中
} catch (Exception e) {
continueReading = false;
}
}
try {
inputStream.close();
} catch (IOException e) {
System.err.println("檔案錯誤");
System.exit(1);
}
}
}
FileNotFoundException)與關閉檔案時的 IO 錯誤(IOException)。read() 方法讀取資料到緩衝區,回傳實際讀取的位元組數,再以 System.out.write() 輸出。finally 區塊或 try-catch 中關閉輸入串流,避免資源洩漏。編譯後執行:java ReadFile 目標檔案.txt
在 JDK 7+ 環境下,建議使用 try-with-resources 語法自動管理資源關閉,並可搭配 Files.copy() 或 BufferedReader 簡化程式碼:
// Java 7+ 簡潔寫法
try (FileInputStream fis = new FileInputStream(args[0])) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
System.out.write(buffer, 0, len);
}
} catch (IOException e) {
System.err.println("讀取失敗:" + e.getMessage());
}