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

Java檔案寫入範例:鍵盤輸入導向檔案

     編輯:J2EE

示範使用 `FileOutputStream` 將標準輸入(鍵盤)資料即時寫入指定檔案,以 `#` 開頭的行作為結束標記。

關鍵類與流程

  • `System.in.read(byte[])`:從標準輸入讀取位元組
  • `FileOutputStream.write(byte[], offset, len)`:寫入檔案
  • `System.out.write(byte[], offset, len)`:同時回顯至螢幕

完整程式碼

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

改進建議

  • 使用 `try-with-resources` 自動關閉流(JDK 7+)
  • 指定字元集 `OutputStreamWriter` 處理中文
  • 生產環境建議使用 `BufferedWriter` 提升效能
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved