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

Java 檔案操作增強工具類(基於 Apache Commons IO)

     編輯:Java 相關知識

背景

JDK 原生 java.io.File 功能極簡,目錄複製、移動、刪除、大小計算皆需自行遞迴實作,程式碼冗長且易出錯。引入 Apache Commons IO 可大幅簡化開發。

Maven 依賴

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

工具類完整程式碼 (FileToolkit.java)

package util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;

public final class FileToolkit {
    private static final Log log = LogFactory.getLog(FileToolkit.class);

    /** 複製檔案或目錄(保持結構完全一致) */
    public static void copyFile(String srcPath, String destDir) throws IOException {
        File src = new File(srcPath);
        File dest = new File(destDir);
        if (src.isDirectory()) FileUtils.copyDirectoryToDirectory(src, dest);
        else if (src.isFile()) FileUtils.copyFileToDirectory(src, dest, true);
    }

    /** 刪除檔案或目錄 */
    public static void deleteFile(String targetPath) throws IOException {
        File target = new File(targetPath);
        if (target.isDirectory()) FileUtils.deleteDirectory(target);
        else if (target.isFile()) target.delete();
    }

    /** 移動檔案或目錄(目標不存在自動建立) */
    public static void moveFile(String srcPath, String destDir) throws IOException {
        File src = new File(srcPath);
        File dest = new File(destDir);
        if (src.isDirectory()) FileUtils.moveDirectoryToDirectory(src, dest, true);
        else if (src.isFile()) FileUtils.moveFileToDirectory(src, dest, true);
    }

    /** 重新命名檔案/目錄 */
    public static boolean renameFile(String srcPath, String newName) {
        String parent = new File(srcPath).getParent();
        String newPath = (parent == null ? "" : parent + File.separator) + newName;
        return new File(srcPath).renameTo(new File(newPath));
    }

    /** 取得檔案或目錄大小(位元組),失敗回傳 -1 */
    public static long genFileSize(String path) {
        File f = new File(path);
        if (f.isFile()) return f.length();
        if (f.isDirectory()) return FileUtils.sizeOfDirectory(f);
        return -1L;
    }

    /** 判斷檔案/目錄是否存在 */
    public static boolean isExist(String path) {
        return new File(path).exists();
    }

    /** 列出目錄下符合副檔名的檔案(非遞迴) */
    public static String[] listFileBySuffix(String folder, String suffix) {
        IOFileFilter filter1 = new SuffixFileFilter(suffix);
        IOFileFilter filter2 = new NotFileFilter(DirectoryFileFilter.INSTANCE);
        FilenameFilter ff = new AndFileFilter(filter1, filter2);
        return new File(folder).list(ff);
    }

    /** 將字串寫入檔案(自動建立父目錄) */
    public static boolean stringToFile(String content, String filePath) {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            File f = new File(filePath);
            if (!f.getParentFile().exists()) f.getParentFile().mkdirs();
            br = new BufferedReader(new StringReader(content));
            bw = new BufferedWriter(new FileWriter(f));
            char[] buf = new char[1024];
            int len;
            while ((len = br.read(buf)) != -1) bw.write(buf, 0, len);
            bw.flush();
            return true;
        } catch (IOException e) {
            log.error("寫入檔案失敗: " + filePath, e);
            return false;
        } finally {
            try { if (br != null) br.close(); } catch (IOException ignored) {}
            try { if (bw != null) bw.close(); } catch (IOException ignored) {}
        }
    }
}

使用範例

// 複製整個目錄
FileToolkit.copyFile("D:/data", "E:/backup");

// 移動單一檔案
FileToolkit.moveFile("D:/log.txt", "E:/archive");

// 取得資料夾大小 (MB)
long mb = FileToolkit.genFileSize("D:/project") / 1024 / 1024;

// 列出所有 .xml 檔
String[] xmls = FileToolkit.listFileBySuffix("D:/config", ".xml");

// 寫入字串到檔案
FileToolkit.stringToFile("...", "D:/out/config.xml");

優點總結

  • 零遞迴程式碼,所有複雜度委託給成熟庫處理
  • 統一拋出 IOException,錯誤處理一致
  • 支援大檔案(內部使用緩衝流)
  • 執行緒安全(Commons IO 內部已處理)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved