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

Java 文件操作核心 API 實戰:創建、讀寫、複製、目錄遞歸完全指南

     編輯:Java 綜合教學

Java 文件操作核心 API 實戰:創建、讀寫、複製、目錄遞歸完全指南

基於 java.io.File 與流 API 的文件操作是 Java 開發基礎技能。本文匯總創建文件/目錄、讀寫文本/二進制、文件複製、遞歸遍歷刪除等高頻場景的標準化代碼範例,採用 Try-with-resources 確保資源安全釋放。

1. 創建文件(單文件)

public void createFileIfNotExists(String path) throws IOException {
    File file = new File(path);
    if (!file.exists()) {
        // 確保父目錄存在
        file.getParentFile().mkdirs();
        boolean created = file.createNewFile();
        System.out.println("文件創建: " + created);
    }
}

2. 創建多級目錄

public void createDirs(String path) {
    File dir = new File(path);
    if (!dir.exists()) {
        boolean created = dir.mkdirs(); // 遞歸創建
        System.out.println("目錄創建: " + created);
    }
}
mkdir() vs mkdirs():mkdir() 僅創建最後一級,父目錄必須存在;mkdirs() 遞歸創建所有不存在的父目錄,推薦始終使用 mkdirs()。

3. 讀取文本文件(按行讀取,自動關閉流)

public String readTextFile(String path) throws IOException {
    StringBuilder content = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line).append(System.lineSeparator());
        }
    }
    return content.toString();
}

4. 寫入文本文件(覆蓋/追加模式)

// 覆蓋模式
public void writeTextFile(String path, String content) throws IOException {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) {
        writer.write(content);
    }
}

// 追加模式
public void appendTextFile(String path, String content) throws IOException {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(path, true))) {
        writer.write(content);
        writer.newLine();
    }
}

5. 二進制文件複製(高效緩衝區)

public void copyBinaryFile(String srcPath, String destPath) throws IOException {
    File src = new File(srcPath);
    if (!src.exists() || src.isDirectory()) {
        throw new FileNotFoundException("源文件不存在: " + srcPath);
    }
    File dest = new File(destPath);
    dest.getParentFile().mkdirs();

    try (FileInputStream in = new FileInputStream(src);
         FileOutputStream out = new FileOutputStream(dest)) {
        byte[] buffer = new byte[8192]; // 8KB
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    }
}

6. 遞歸遍歷目錄樹(打印/收集所有文件)

public void listAllFiles(File dir, List result) {
    if (dir == null || !dir.exists()) return;
    if (dir.isFile()) {
        result.add(dir);
    } else {
        File[] children = dir.listFiles();
        if (children != null) {
            for (File child : children) {
                listAllFiles(child, result);
            }
        }
    }
}

// 使用示例
List allFiles = new ArrayList<>();
listAllFiles(new File("D:/data"), allFiles);
allFiles.forEach(f -> System.out.println(f.getAbsolutePath()));

7. 遞歸刪除目錄樹(後序遍歷:先刪子項,再刪自身)

public void deleteRecursively(File file) {
    if (file == null || !file.exists()) return;
    if (file.isDirectory()) {
        File[] children = file.listFiles();
        if (children != null) {
            for (File child : children) {
                deleteRecursively(child);
            }
        }
    }
    boolean deleted = file.delete();
    if (!deleted) {
        System.err.println("刪除失敗: " + file.getAbsolutePath());
    }
}

8. Java 7+ NIO.2 一行代碼替代方案

 lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);

// 寫入文件
Files.write(Paths.get("out.txt"), "內容".getBytes(StandardCharsets.UTF_8));

// 複製文件
Files.copy(Paths.get("src"), Paths.get("dest"), StandardCopyOption.REPLACE_EXISTING);

// 遞歸刪除
Files.walkFileTree(Paths.get("dir"), new SimpleFileVisitor() {
    @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Files.delete(file); return FileVisitResult.CONTINUE;
    }
    @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        Files.delete(dir); return FileVisitResult.CONTINUE;
    }
});

核心最佳實踐總結

  • ✅ 統一使用 try-with-resources 自動關閉流(Java 7+)。
  • ✅ 文件操作前檢查 exists()、isDirectory(),異常拋出具體信息。
  • ✅ 路徑拼接用 File 構造器或 Paths.get(),避免手動拼接分隔符。
  • ✅ 大文件複製/讀寫必須使用緩衝區(BufferedInputStream/BufferedOutputStream 或 NIO FileChannel)。
  • ✅ 新項目優先選擇 java.nio.file.Files API,功能更強、異常更精確、支持符號鏈接與異步操作。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved