示範使用 `FileOutputStream` 將標準輸入(鍵盤)資料即時寫入指定檔案,以 `#` 開頭的行作為結束標記。
import java.io.*;
public class WriteFile {
public static void main(String[] args) {
if (args.length == 0) {
System.err.println("用法: java WriteFile <檔案名>");
System.exit(1);
}
byte[] buf = new byte[1024];
try (FileOutputStream out = new FileOutputStream(args[0])) {
System.out.println("開始輸入(以 # 開頭的行結束):");
while (true) {
int n = System.in.read(buf);
if (n == -1) break; // EOF
System.out.write(buf, 0, n); // 螢幕回顯
if (buf[0] == '#') break; // 結束條件
out.write(buf, 0, n);
}
} catch (IOException e) {
System.err.println("檔案錯誤: " + e.getMessage());
System.exit(1);
}
}
}