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

Java 檔案操作工具類庫完整實作:建立、刪除、複製、移動、屬性與大小查詢一站式解決

     編輯:Java 相關知識

封裝一個功能完整、易於複用的 Java 檔案操作工具包,涵蓋檔案/目錄的建立、刪除、複製、移動、屬性讀寫與大小計算六大核心功能。本文提供模組化原始碼,採用遞迴與緩衝流優化效能,並處理常見邊界條件(存在性檢查、權限驗證、覆蓋策略等),可直接整合至專案中。

模組架構概覽

  • Create:建立檔案與目錄
  • Delete:刪除檔案與目錄(遞迴)
  • Copy:複製檔案與目錄(支援覆蓋模式)
  • Move:移動檔案與目錄(複製+刪除實現)
  • Attribute:讀取與設定檔案屬性(可讀/可寫/可執行)
  • Size:計算檔案或目錄總大小(遞迴疊加)

核心功能實作重點

建立操作

public void createFile(String filePath) {
    File file = new File(filePath);
    if (file.exists()) throw new RuntimeException("File already exists: " + filePath);
    try (FileOutputStream fos = new FileOutputStream(file)) {
        // Windows 下需實際寫入才能看到檔案
    }
}
public void createDir(String filePath) {
    File file = new File(filePath);
    if (file.exists()) throw new RuntimeException("Directory already exists: " + filePath);
    file.mkdirs();
}

刪除操作(遞迴清空目錄)

public boolean deleteDir(String filePath) throws IOException {
    File file = new File(filePath);
    if (!file.exists() || !file.isDirectory()) return false;
    File[] files = file.listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.isDirectory()) deleteDir(f.getAbsolutePath());
            else f.delete();
        }
    }
    return file.delete(); // 最後刪除空目錄本身
}

複製操作(緩衝流 + 覆蓋控制)

public int copyFile(String src, String dest, int type) throws IOException {
    File srcFile = new File(src), destFile = new File(dest);
    // 存在性、可讀性、目標目錄可寫性檢查...
    if (destFile.exists()) {
        if (type == 1) destFile.delete(); // 覆蓋
        else return 2; // 不覆蓋
    }
    try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile))) {
        byte[] buffer = new byte[5120];
        int len;
        while ((len = bis.read(buffer)) != -1) bos.write(buffer, 0, len);
        return 1;
    }
}

目錄複製採用遞迴:建立目標目錄後,遍歷來源目錄下檔案與子目錄,檔案呼叫 copyFile(),子目錄遞迴呼叫 copyDirectory()。

移動操作

因 renameTo() 跨檔案系統失敗風險高,採用「複製成功後刪除來源」策略:

public int move(String src, String dest, int type) throws IOException {
    Copy copy = new Copy(); Delete del = new Delete();
    File srcFile = new File(src);
    if (!srcFile.exists()) throw new RuntimeException("Source not found: " + src);
    int result = srcFile.isFile() 
        ? copy.copyFile(src, dest, type) 
        : copy.copyDirectory(src, dest, type);
    if (result == 1) srcFile.isFile() ? del.deleteFile(src) : del.deleteDir(src);
    return result;
}

屬性讀寫與大小計算


// 屬性查看
public void lookAttribute(String fileName) {
    File f = new File(fileName);
    System.out.printf("Read:%b Write:%b Execute:%b%n", f.canRead(), f.canWrite(), f.canExecute());
}
// 屬性設定(ownerOnly 限定擁有者)
public boolean setAttribute(String fileName, boolean readable, boolean writable, boolean executable, boolean ownerOnly) {
    File f = new File(fileName);
    return f.setReadable(readable, ownerOnly) 
        && f.setWritable(writable, ownerOnly) 
        && f.setExecutable(executable, ownerOnly);
}
// 大小計算(遞迴)
public static long getSize(String path) throws IOException {
    File f = new File(path);
    if (!f.exists()) throw new RuntimeException("Not found: " + path);
    if (f.isFile()) return f.length();
    long sum = 0;
    for (String child : f.list()) sum += getSize(path + "/" + child);
    return sum;
}

使用建議與擴展方向

  • 所有方法拋出 RuntimeException 封裝底層異常,呼叫端可統一捕獲。
  • 大檔案複製建議升級為 NIO FileChannel.transferTo() 提升效能。
  • 可進一步加入檔案監聽、壓縮/解壓、校驗和碼等功能構建完整檔案管理模組。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved