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

Java 生成文本文件工具類:PrintWriter + FileWriter 封裝與資源安全關閉

     編輯:Java 相關知識

簡潔的文本文件寫入工具類 Result,封裝 FileWriter + PrintWriter,提供 aLine(String) 寫入行、finish() 刷新關閉,構造函數自動打開流,異常捕獲打印錯誤流。

代碼

public class Result {
    private FileWriter writer;
    private PrintWriter pw;
    public Result() {
        try {
            writer = new FileWriter("result.txt");
            pw = new PrintWriter(writer);
        } catch (IOException e) { System.err.println(e); }
    }
    public void aLine(String in) { pw.println(in); }
    public void finish() {
        try { pw.flush(); writer.close(); }
        catch (IOException e) { System.err.println(e); }
    }
}

改進建議(生產級)

  • 實現 AutoCloseable,支援 try (Result r = new Result()) { ... } 自動關閉。
  • 構造函數接受 File 或路徑參數,支援指定編碼 new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)。
  • aLine 返回 this 支援鏈式調用。
  • 異常拋出而非吞噬,讓調用者決策處理策略。
  • 大文件場景考慮 BufferedWriter 顯式緩衝區大小。

現代替代

Java 7+ Files.newBufferedWriter(Path, StandardOpenOption.CREATE, ...)、Java 11+ Files.writeString(Path, content, StandardOpenOption.APPEND) 單行寫入更簡潔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved