每次讀個配置文件、寫個臨時結果,都要寫 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);
Files.lines() 流式處理或分塊讀取。UTF-8,避免默認編碼差異(Windows GBK vs Linux UTF-8)。null/false 便於腳本調用,核心業務邏輯請拋出異常或用 Result 對象攜帶錯誤信息。// 一行讀取
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 內部已處理緩衝、編碼、異常,首選標準庫,無需自造輪子。