Web 專案部署後,常需在 WebRoot (或 webapps/專案名) 下動態建立資料夾與檔案。本文提供完整工具類套件,涵蓋建立、複製、移動、刪除、屬性檢視、大小計算等核心檔案操作。
public boolean doTest() {
// 相對路徑:../webapps/專案名/資料夾/檔案
String path = "../webapps/FileTest/reportFiles/aa.jsp";
boolean isDone = false;
File file = new File(path);
if (file.exists())
throw new RuntimeException("File: " + path + " is already exist");
try {
isDone = file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return isDone;
}
關鍵點:使用相對路徑 ../webapps/... 定位部署目錄,File.createNewFile() 會自動建立父目錄 (若不存在)。
public class Attribute {
// 檢視可讀/可寫/可執行
public void lookAttribute(String fileName) { /* ... */ }
// 設定屬性 (部分 Windows 下無效)
public boolean setAttribute(String fileName, boolean readable, boolean writable,
boolean executable, boolean ownerOnly) { /* ... */ }
}
public class Copy {
// 複製檔案
// type: 1=覆蓋, 2=不覆蓋取消
// 回傳: 1=成功, 2=目標存在且不覆蓋, 0=其他失敗
public int copyFile(String source_name, String dest_name, int type) throws IOException { /* ... */ }
// 複製目錄 (遞迴)
public int copyDirectory(String source_name, String dest_name, int type) throws IOException { /* ... */ }
}
特性:判斷來源不存在/不可讀、目標已存在/不可寫/目錄不存在等異常情況;使用緩衝流 (5KB) 高效複製。
public class Create {
public boolean createFile(String filePath) { /* ... */ } // 檔案存在拋異常
public boolean createDir(String filePath) { /* ... */ } // mkdirs 自動建立父目錄
}
public class Delete {
public boolean deleteFile(String filePath) throws IOException { /* ... */ }
public boolean deleteDir(String filePath) throws IOException {
// 遞迴刪除子目錄/檔案,最後刪除自身目錄
/* ... */
}
}
public class Move {
public int move(String source_name, String dest_name, int type) throws IOException {
Copy copy = new Copy();
Delete delete = new Delete();
// 複製成功後刪除來源
/* ... */
}
}
public class Size {
public static long getSize(String fileName) throws IOException {
// 檔案直接回傳 length(),目錄遞迴累加
/* ... */
}
}
ServletContext.getRealPath("/") 取得部署根路徑,拼接相對路徑,避免相對路徑在不同伺服器/部署方式下失效java.nio.file 原子操作FileChannel.transferTo/transferFrom 零拷貝提升效能file.encoding 一致java.nio.file.Files、Path、StandardCopyOption 提供更豐富、原子化、異步的檔案操作 API,建議新專案優先採用:
Files.createDirectories(path);
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
Files.walkFileTree(root, new SimpleFileVisitor() { /* 刪除/計算大小 */ });
本套件提供傳統 java.io.File 為基礎的完整檔案操作工具,涵蓋 Web 專案常見需求。理解其實作細節 (緩衝流、遞迴、異常處理) 有助於遷移至現代 NIO.2 API 或排查檔案操作相關問題。