文件操作是 Java 開發中高頻需求。本文提供一個功能豐富的 FileUtil 工具類,涵蓋文件讀寫、複製、刪除、目錄管理、ZIP 壓縮解壓、編碼處理等核心功能,代碼經過生產環境驗證,可直接集成到項目中。
SaveFileByPhysicalDir 使用 8KB 緩衝區高效寫入大文件。saveAsFileOutputStream 自動創建父目錄,支持 UTF-8 編碼。write 和 writeLog 支持帶時間戳的日誌記錄。copyToFile:單文件複製,使用字節數組緩衝。copyDir:遞歸複製整個目錄結構。copyFile:通用文件複製,4KB 緩衝區,正確關閉流。deleteDirectory:遞歸刪除目錄及所有內容。deleteFromName:刪除單個文件。checkExist:判斷文件是否存在且為文件類型。getSize:獲取文件大小(字節),不存在返回 0,不可讀返回 -1。zip 方法遞歸遍歷目錄,使用 ZipOutputStream 支持中文路徑(UTF-8 編碼)。unZip 基於 Apache Ant 的 Expand 任務實現,一鍵解壓到指定目錄,自動處理編碼。renameFile:複製後刪除源文件實現重命名。readTextFile:UTF-8 編碼讀取文本文件全部內容。private static void zip(ZipOutputStream zOut, File file, String base) {
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
zOut.putNextEntry(new ZipEntry(base + "/"));
base = (base.length() == 0 ? "" : base + "/");
if (listFiles != null) {
for (File f : listFiles) zip(zOut, f, base + f.getName());
}
} else {
if (base == "") base = file.getName();
zOut.putNextEntry(new ZipEntry(base));
writeFile(zOut, file); // 緩衝讀寫文件內容
}
}
public static void unZip(String zipPath, String destinationPath) {
File zipFile = new File(zipPath);
Project proj = new Project();
Expand expand = new Expand();
expand.setProject(proj);
expand.setSrc(zipFile);
expand.setDest(new File(destinationPath));
expand.setEncoding("UTF-8");
expand.execute(); // 一行代碼完成解壓
}
解壓功能依賴 ant.jar,請從 Apache Ant 官網 下載並加入項目 classpath。
try-catch-finally 確保資源釋放。BufferedInputStream/OutputStream)。