首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Web 專案實戰:Java 在部署目錄 WebRoot 下建立資料夾與檔案操作工具類完整實作

     編輯:Java 相關知識

Web 專案部署後,常需在 WebRoot (或 webapps/專案名) 下動態建立資料夾與檔案。本文提供完整工具類套件,涵蓋建立、複製、移動、刪除、屬性檢視、大小計算等核心檔案操作。

核心範例:在 WebRoot 下建立檔案


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() 會自動建立父目錄 (若不存在)。

完整檔案操作工具類套件 (package fileOperation)

1. Attribute — 屬性檢視與設定


public class Attribute {
    // 檢視可讀/可寫/可執行
    public void lookAttribute(String fileName) { /* ... */ }
    // 設定屬性 (部分 Windows 下無效)
    public boolean setAttribute(String fileName, boolean readable, boolean writable,
                                boolean executable, boolean ownerOnly) { /* ... */ }
}

2. Copy — 檔案與目錄複製 (支援覆蓋控制)


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) 高效複製。

3. Create — 建立檔案與目錄


public class Create {
    public boolean createFile(String filePath) { /* ... */ }  // 檔案存在拋異常
    public boolean createDir(String filePath) { /* ... */ }   // mkdirs 自動建立父目錄
}

4. Delete — 刪除檔案與目錄 (遞迴)


public class Delete {
    public boolean deleteFile(String filePath) throws IOException { /* ... */ }
    public boolean deleteDir(String filePath) throws IOException {
        // 遞迴刪除子目錄/檔案,最後刪除自身目錄
        /* ... */
    }
}

5. Move — 移動檔案/目錄 (複製+刪除)


public class Move {
    public int move(String source_name, String dest_name, int type) throws IOException {
        Copy copy = new Copy();
        Delete delete = new Delete();
        // 複製成功後刪除來源
        /* ... */
    }
}

6. Size — 計算檔案/目錄佔用空間


public class Size {
    public static long getSize(String fileName) throws IOException {
        // 檔案直接回傳 length(),目錄遞迴累加
        /* ... */
    }
}

使用情境與注意事項

  • 路徑解析:Web 專案中推薦使用 ServletContext.getRealPath("/") 取得部署根路徑,拼接相對路徑,避免相對路徑在不同伺服器/部署方式下失效
  • 權限問題:確保 JVM 進程對目標目錄有讀寫執行權限 (Linux 下特別注意)
  • 並發安全:工具類方法非執行緒安全,多執行緒環境需外部同步或使用 java.nio.file 原子操作
  • 大檔案複製:可升級為 FileChannel.transferTo/transferFrom 零拷貝提升效能
  • 編碼問題:檔案名含中文時,確保系統預設編碼與 JVM file.encoding 一致

現代化替代方案 (Java 7+)

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 或排查檔案操作相關問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved