封裝一個功能完整、易於複用的 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 封裝底層異常,呼叫端可統一捕獲。FileChannel.transferTo() 提升效能。