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

Java 檔案與目錄操作完全指南:建立、臨時檔、最佳實踐

     編輯:Java 相關知識

核心 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

最佳實踐與注意事項

  1. 路徑分隔符:使用 File.separator 而非硬編碼 / 或 \
  2. 原子性:createNewFile() 是原子操作,適合分散式鎖實作
  3. 臨時檔清理:JVM 關閉時自動刪除 deleteOnExit() 註冊的檔案,或用 Files.createTempFile() (NIO.2) 配合 try-with-resources
  4. 權限檢查:建立前先用 canWrite() 檢查目錄寫入權限
  5. NIO.2 替代方案:Java 7+ 建議使用 Files.createFile()、Files.createDirectories()、Files.createTempFile(),提供更豐富的屬性控制與例外資訊

常見錯誤排查

錯誤現象可能原因解決方案
createNewFile() 回傳 false檔案已存在、路徑是目錄、父目錄不存在、無寫入權限依序檢查上述條件
mkdirs() 回傳 false路徑中有檔案同名、無權限、磁碟滿檢查路徑衝突、權限、磁碟空間
臨時檔名亂碼Windows 路徑含中文、編碼不一致使用 getCanonicalPath() 獲取標準路徑
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved