在 Java 開發中,文件操作是基礎且高頻的需求。本文將系統講解如何創建文件、寫入內容、讀取數據以及刪除文件,並提供一個可直接用於生產環境的工具類封裝。
項目中常遇到需通過 HTTP 請求獲取較大 JSON 數據(如 300KB 左右)並持久化保存的場景。為避免重複請求,將數據以文件形式落地,後續直接讀取本地文件即可,顯著提升響應速度並降低外部依賴風險。
下方代碼整合了創建、寫入(追加模式)、刪除三大核心功能,採用靜態方法設計,開箱即用:
package com.file.run;
import java.io.*;
import java.util.UUID;
public class ForFile {
private static final String BASE_PATH = "D:\\file\\";
/**
* 創建文件並寫入初始內容
* @param fileName 文件名(不含副檔名)
* @param fileContent 初始內容
* @return 是否創建成功
*/
public static boolean createFile(String fileName, String fileContent) {
String fullPath = BASE_PATH + fileName + ".txt";
File file = new File(fullPath);
try {
if (!file.exists()) {
boolean created = file.createNewFile();
if (created) {
System.out.println("成功創建文件: " + fullPath);
writeFileContent(fullPath, fileContent);
}
return created;
}
return false; // 文件已存在
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 追加寫入內容(保留原有數據)
* @param filePath 完整文件路徑
* @param newStr 新增內容
* @return 是否寫入成功
*/
public static boolean writeFileContent(String filePath, String newStr) {
File file = new File(filePath);
String line = newStr + System.lineSeparator();
StringBuilder buffer = new StringBuilder();
// 讀取原有內容
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr)) {
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp).append(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
buffer.append(line);
// 寫入合併後內容
try (FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos)) {
pw.write(buffer.toString());
pw.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 刪除指定文件
* @param fileName 文件名(不含副檔名)
* @return 是否刪除成功
*/
public static boolean delFile(String fileName) {
String fullPath = BASE_PATH + fileName + ".txt";
File file = new File(fullPath);
if (file.exists()) {
return file.delete();
}
return false;
}
// 測試入口
public static void main(String[] args) {
String uniqueName = UUID.randomUUID() + "myfile";
String content = "我的夢說別停留等待,就讓光芒折射淚濕的瞳孔,映出心中最想擁有的彩虹";
createFile(uniqueName, content);
}
}
StandardCharsets.UTF_8 避免中文亂碼Files.write(..., StandardOpenOption.APPEND) 直接追加FileLockFile.createNewFile() 僅創建文件,不創建父目錄,需先 file.getParentFile().mkdirs()\\ 或使用 File.separator掌握這套模式,即可輕鬆應對日誌記錄、數據緩存、配置持久化等多數文件操作場景。