示範使用 `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);
}
}
}