首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 讀取檔案完整範例:使用 FileInputStream 實現檔案輸出

     編輯:Java 相關知識

Java 讀取檔案的基礎實作

在 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);
        }
    }
}

程式碼解析

  • 緩衝區設計:使用 1024 位元組的 byte 陣列作為緩衝區,平衡記憶體使用與讀取效能。
  • 異常處理:分別處理檔案不存在(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());
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved