生產級專案常需處理檔案/目錄建立、刪除、讀寫、壓縮、屬性讀取、大小格式化、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 執行緒 |
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 管理頁面換入/出。
// 壓縮
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);
}
}
}
public static class FileProperties {
private String id, fileName, fileSize; // getter/setter 省略
}
工具類封裝細節、屏蔽異常、統一資源管理,讓業務代碼聚焦核心邏輯,是中大型專案基礎設施建設的標準動作。