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

Java 快速開發利器:一鍵讀寫文件的工具方法封裝

     編輯:Java 程式設計入門

痛點:樣板代碼太多

每次讀個配置文件、寫個臨時結果,都要寫 try-with-resources、BufferedReader、循環讀行、異常處理……影響開發流暢度。

極簡讀文件 → 字符串

/**
 * 讀取整個文件內容為字符串,失敗返回 null。
 * 適用於小文件(< 100MB),大文件請用流式處理。
 */
public static String readFile(String filePath) {
    File file = new File(filePath);
    if (!file.exists() || !file.isFile()) return null;
    try (FileReader fr = new FileReader(file)) {
        char[] buffer = new char[(int) file.length()];
        int read = fr.read(buffer);
        return new String(buffer, 0, read);
    } catch (IOException e) {
        return null; // 靜默失敗,適合工具庫;關鍵業務請拋出異常
    }
}

極簡寫文件:字符串 → 文件

/**
 * 將字符串寫入文件,自動創建父目錄,覆蓋模式。
 * @return 成功 true,失敗 false
 */
public static boolean writeFile(String filePath, String content) {
    File file = new File(filePath);
    File parent = file.getParentFile();
    if (parent != null && !parent.exists() && !parent.mkdirs()) {
        return false; // 無法創建目錄
    }
    try (FileWriter fw = new FileWriter(file)) {
        fw.write(content);
        return true;
    } catch (IOException e) {
        return false;
    }
}

進階版:支援編碼、追加、行分隔符

public static boolean writeFile(String filePath, String content,
                                String charset, boolean append) {
    File file = new File(filePath);
    File parent = file.getParentFile();
    if (parent != null && !parent.exists() && !parent.mkdirs()) return false;
    try (OutputStreamWriter osw = new OutputStreamWriter(
            new FileOutputStream(file, append), charset)) {
        osw.write(content);
        return true;
    } catch (IOException e) {
        return false;
    }
}

// 讀取指定編碼
public static String readFile(String filePath, String charset) {
    File file = new File(filePath);
    if (!file.exists() || !file.isFile()) return null;
    try (InputStreamReader isr = new InputStreamReader(
            new FileInputStream(file), charset)) {
        char[] buffer = new char[(int) file.length()];
        int read = isr.read(buffer);
        return new String(buffer, 0, read);
    } catch (IOException e) {
        return null;
    }
}

使用示例

// 讀配置
String json = FileUtils.readFile("config/app.json", "UTF-8");
if (json != null) {
    Config cfg = Gson.fromJson(json, Config.class);
}

// 寫日誌
FileUtils.writeFile("logs/app.log", "[" + Instant.now() + "] 啟動完成\n", "UTF-8", true);

避坑提醒

  • 大文件 OOM:以上方法全量讀入內存,超過百 MB 請改用 Files.lines() 流式處理或分塊讀取。
  • 編碼不一致:跨平台部署務必顯式指定 UTF-8,避免默認編碼差異(Windows GBK vs Linux UTF-8)。
  • 靜默失敗風險:工具方法返回 null/false 便於腳本調用,核心業務邏輯請拋出異常或用 Result 對象攜帶錯誤信息。

現代 JDK 替代方案(JDK 11+)

// 一行讀取
String content = Files.readString(Path.of("file.txt"), StandardCharsets.UTF_8);
// 一行寫入
Files.writeString(Path.of("file.txt"), content, StandardCharsets.UTF_8,
        StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
JDK 11 Files.readString/writeString 內部已處理緩衝、編碼、異常,首選標準庫,無需自造輪子。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved