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

Java檔案讀取範例:將檔案內容輸出至螢幕

     編輯:J2EE

示範使用 `FileInputStream` 讀取指定檔案並輸出至標準輸出,適合查看文字檔或二進位資料。

核心程式碼

import java.io.*;

public class ReadFile {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("用法: java ReadFile <檔案名>");
            System.exit(1);
        }
        byte[] buf = new byte[1024];
        try (FileInputStream in = new FileInputStream(args[0])) {
            int n;
            while ((n = in.read(buf)) != -1) {
                System.out.write(buf, 0, n);
            }
        } catch (IOException e) {
            System.err.println("讀取錯誤: " + e.getMessage());
            System.exit(1);
        }
    }
}

進階用法

  • 文字檔建議使用 `Files.readAllLines(Path)` 或 `BufferedReader` 按行處理
  • 大檔案可搭配 `MappedByteBuffer` 記憶體映射
  • 指定編碼:`new InputStreamReader(in, StandardCharsets.UTF_8)`
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved