核心 API 概覽
| 方法 | 用途 | 關鍵行為 |
createNewFile() | 建立空檔案 | 檔案存在回傳 false;父目錄必須存在 |
mkdir() | 建立單層目錄 | 父目錄不存在則失敗 |
mkdirs() | 建立多層目錄 | 自動建立不存在的父目錄 |
createTempFile(prefix, suffix, dir) | 建立臨時檔案 | 自動生成唯一檔名;可指定目錄或用系統預設 |
實用工具類:CreateFileUtil
封裝常見操作,包含完整錯誤處理與日誌輸出:
建立單一檔案
public static boolean createFile(String destFileName) {
File file = new File(destFileName);
if (file.exists()) { log("檔案已存在"); return false; }
if (destFileName.endsWith(File.separator)) { log("路徑不能是目錄"); return false; }
// 確保父目錄存在
File parent = file.getParentFile();
if (!parent.exists() && !parent.mkdirs()) { log("建立父目錄失敗"); return false; }
try {
return file.createNewFile();
} catch (IOException e) { log("建立失敗: " + e.getMessage()); return false; }
}
建立多層目錄
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) { log("目錄已存在"); return false; }
if (!destDirName.endsWith(File.separator)) destDirName += File.separator;
return dir.mkdirs();
}
建立臨時檔案
public static String createTempFile(String prefix, String suffix, String dirName) {
File dir = (dirName == null) ? null : new File(dirName);
if (dir != null && !dir.exists() && !createDir(dirName)) return null;
try {
File tempFile = (dir == null) ?
File.createTempFile(prefix, suffix) :
File.createTempFile(prefix, suffix, dir);
return tempFile.getCanonicalPath();
} catch (IOException e) { log("建立失敗: " + e.getMessage()); return null; }
}
執行範例與輸出
public static void main(String[] args) {
String dirName = "D:/work/temp/temp0/temp1";
createDir(dirName); // 建立多層目錄
createFile(dirName + "/temp2/tempFile.txt"); // 自動建立中間目錄
// 指定目錄建立 10 個臨時檔
for (int i = 0; i < 10; i++)
System.out.println(createTempFile("temp", ".txt", dirName));
// 系統預設臨時目錄建立 10 個
for (int i = 0; i < 10; i++)
System.out.println(createTempFile("temp", ".txt", null));
}
輸出範例
建立目錄 D:/work/temp/temp0/temp1 成功!
建立單一檔案 D:/work/temp/temp0/temp1/temp2/tempFile.txt 成功!
建立了臨時檔案:D:\work\temp\temp0\temp1\temp5171.txt
...
在預設目錄下建立了臨時檔案:C:\Users\Admin\AppData\Local\Temp\temp5181.txt
最佳實踐與注意事項
- 路徑分隔符:使用
File.separator 而非硬編碼 / 或 \
- 原子性:
createNewFile() 是原子操作,適合分散式鎖實作
- 臨時檔清理:JVM 關閉時自動刪除
deleteOnExit() 註冊的檔案,或用 Files.createTempFile() (NIO.2) 配合 try-with-resources
- 權限檢查:建立前先用
canWrite() 檢查目錄寫入權限
- NIO.2 替代方案:Java 7+ 建議使用
Files.createFile()、Files.createDirectories()、Files.createTempFile(),提供更豐富的屬性控制與例外資訊
常見錯誤排查
| 錯誤現象 | 可能原因 | 解決方案 |
| createNewFile() 回傳 false | 檔案已存在、路徑是目錄、父目錄不存在、無寫入權限 | 依序檢查上述條件 |
| mkdirs() 回傳 false | 路徑中有檔案同名、無權限、磁碟滿 | 檢查路徑衝突、權限、磁碟空間 |
| 臨時檔名亂碼 | Windows 路徑含中文、編碼不一致 | 使用 getCanonicalPath() 獲取標準路徑 |