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

Java 檔案工具類大全:目錄操作、IO 流讀寫、壓縮解壓、屬性讀取、大小格式化、Excel 列印整合

     編輯:Java 綜合教學

Java 檔案工具類大全

生產級專案常需處理檔案/目錄建立、刪除、讀寫、壓縮、屬性讀取、大小格式化、Excel 列印等操作。本工具類整合 Apache Commons IO、NIO.2、MappedByteBuffer、JCOM/Jacob 等技術,提供線程安全、資源自動釋出、異常屏蔽的統一入口。

核心功能矩陣

方法功能關鍵技術點
`mkdirs(path)`遞歸建立目錄`File.mkdirs()`,存在性檢查
`deleteAll(rootPath)`刪除目錄下所有檔案`FileUtils.forceDelete()`,空目錄保留
`deleteFile(fileName)`刪除單一檔案`file.exists() && file.isFile()` 守衛
`saveFileFromInputStream(in, outPath)`輸入流存檔1MB 緩衝區,`flush()` 確保落盤
`readFileByLines(fileName)`按行讀取文本`BufferedReader`,`
` 換行標記
`readFileByChars(fileName)`按字符讀取文本`InputStreamReader`,過濾 `\r` 避免雙換行
`readFileByBytes(fileName)`高效讀二進制/大檔`MappedByteBuffer` 記憶體映射,零拷貝
`loadProperty(filePath)`讀取 Properties 配置`Properties.load(Reader)`
`FormetFileSize(bytes)`位元組轉人類可讀`DecimalFormat`,B/K/M/G 自動單位
`zip(srcFiles[], zipFile)`多檔打包 ZIP`ZipOutputStream`,逐檔 `putNextEntry`
`unZip(zipFile, destDir)`解壓 ZIP 到目錄`ZipFile.entries()` 遍歷,流式寫入
`printExcel4Jcom(path)`JCOM 後台列印 Excel需進程模式啟動,`ExcelApplication` COM 介面
`printExcel4Jacob(path)`Jacob 後台列印 Excel`ActiveXComponent`,`Dispatch.call(PrintOut)`,STA 執行緒

關鍵實現細節解析

1. MappedByteBuffer 大檔案零拷貝讀取

public static byte[] readFileByBytes(String fileName) {
    try (FileChannel fc = new RandomAccessFile(fileName, "r").getChannel()) {
        MappedByteBuffer buf = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        buf.load(); // 強制載入物理記憶體
        byte[] result = new byte[(int) fc.size()];
        if (buf.remaining() > 0) buf.get(result, 0, buf.remaining());
        return result;
    } catch (IOException e) { throw new UncheckedIOException(e); }
}

適用於 >100MB 大檔,避免 JVM 堆壓力,OS 管理頁面換入/出。

2. 壓縮/解壓流式處理,記憶體恆定

// 壓縮
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) {
    for (File src : srcFiles) {
        out.putNextEntry(new ZipEntry(src.getName()));
        try (FileInputStream in = new FileInputStream(src)) {
            byte[] buf = new byte[1024]; int len;
            while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
        }
        out.closeEntry();
    }
}

// 解壓
try (ZipFile zf = new ZipFile(zipFile)) {
    for (Enumeration<?> e = zf.entries(); e.hasMoreElements(); ) {
        ZipEntry entry = (ZipEntry) e.nextElement();
        try (InputStream in = zf.getInputStream(entry);
             OutputStream out = new FileOutputStream(destDir + entry.getName())) {
            byte[] buf = new byte[1024]; int len;
            while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
        }
    }
}

3. Excel 列印雙引擎:JCOM (純 Java) vs Jacob (Windows COM)

  • JCOM:無需安裝 Office,純 Java 實現 COM 協定,適合 Linux 伺服器無頭模式。
  • Jacob:橋接真實 Microsoft Excel COM 物件,渲染保真度最高,需 Windows + Office 安裝,服務需以進程模式啟動(非服務模式)。
  • 兩者皆需 `ComThread.InitSTA()` / `Release()` 管理單執行緒單元模式。

FileProperties 內部類:統一檔案元資料傳輸

public static class FileProperties {
    private String id, fileName, fileSize; // getter/setter 省略
}

使用建議與擴展方向

  1. 引入 Apache Commons IO `FileUtils` 簡化刪除/複製/比較。
  2. 2. NIO.2 `Files` API 替代舊 `File` API(路徑操作、屬性讀取、走訪)。 3. 壓縮支援 GZIP、TAR、7z 等格式擴展。 4. 列印支援 PDF、Word、圖片直印,抽象 `PrintService` 介面多策略。 5. 異常統一包裝為 `FileOperationException`,上層統一處理。

工具類封裝細節、屏蔽異常、統一資源管理,讓業務代碼聚焦核心邏輯,是中大型專案基礎設施建設的標準動作。

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