JSP 中透過 `java.io.File` 類進行伺服器端文件系統操作。本文系統整理 File 類三大建構子、十一大屬性獲取方法、目錄建立/列舉/過濾、刪除操作,附代碼範例與 JSP 部署路徑陷阱提醒。
new File(String filename) // 相對於當前工作目錄
new File(String directoryPath, String filename) // 指定目錄 + 檔名
new File(File dir, String filename) // 指定 File 目錄物件 + 檔名
關鍵陷阱:JSP 引擎啟動於 `bin` 目錄,使用相對路徑 `new File("data.txt")` 實際指向 `$CATALINA_HOME/bin/data.txt`,非 WebApp 根目錄。建議使用 `application.getRealPath("/")` 取得 WebApp 絕對路徑再拼接。
| 方法 | 回傳值 | 說明 |
|---|---|---|
| getName() | String | 檔名 (含副檔名) |
| canRead() | boolean | 是否可讀 |
| canWrite() | boolean | 是否可寫 |
| exists() | boolean | 是否存在 |
| length() | long | 檔案大小 (bytes) |
| getAbsolutePath() | String | 絕對路徑 |
| getParent() | String | 父目錄路徑 |
| isFile() | boolean | 是否為一般檔案 |
| isDirectory() | boolean | 是否為目錄 |
| isHidden() | boolean | 是否為隱藏檔 |
| lastModified() | long | 最後修改時間 (ms since 1970) |
File dir = new File(realPath, "upload");
if (!dir.exists()) dir.mkdir(); // 僅建立單層,多層用 mkdirs()
// 全部檔案 (字串陣列)
String[] names = dir.list();
// 全部檔案 (File 物件陣列,含路徑資訊)
File[] files = dir.listFiles();
File[] imgFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".png");
}
});
file.delete(); // 目錄必須為空才能刪除,非空目錄需遞歸刪除子項
<%
// 取得 WebApp 根目錄絕對路徑
String webRoot = application.getRealPath("/");
File uploadDir = new File(webRoot, "uploads");
// 後續操作基於 uploadDir
%>
掌握 File 類核心 API 與 WebApp 路徑解析技巧,能安全高效實現 JSP 文件上傳、下載、管理、批次處理等功能。