Javaによるフォルダのコピー処理

  1. 単層フォルダのコピー =================
package com.itbianma02;

import java.io.*;

public class FolderCopy {
    public static void main(String[] args) throws IOException {
        File sourceDir = new File("D:\\資料庫\\人事");
        String dirName = sourceDir.getName();
        File targetDir = new File("myDemo", dirName);
        
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        
        File[] files = sourceDir.listFiles();
        for (File sourceFile : files) {
            String fileName = sourceFile.getName();
            File targetFile = new File(targetDir, fileName);
            copyFile(sourceFile, targetFile);
        }
    }

    private static void copyFile(File source, File target) throws IOException {
        try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(source));
             BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(target))) {
            
            byte[] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) != -1) {
                output.write(buffer, 0, length);
            }
        }
    }
}
  1. ネストされたフォルダのコピー =====================
package com.itbianma02;

import java.io.*;

public class NestedFolderCopy {
    public static void main(String[] args) throws IOException {
        File source = new File("D:\\資料庫\\需求");
        File target = new File("myDemo");
        copyDirectory(source, target);
    }

    private static void copyDirectory(File source, File target) throws IOException {
        if (source.isDirectory()) {
            String dirName = source.getName();
            File newDir = new File(target, dirName);
            
            if (!newDir.exists()) {
                newDir.mkdirs();
            }
            
            File[] files = source.listFiles();
            for (File file : files) {
                copyDirectory(file, newDir);
            }
        } else {
            File newFile = new File(target, source.getName());
            copyFile(source, newFile);
        }
    }

    private static void copyFile(File source, File target) throws IOException {
        try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(source));
             BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(target))) {
            
            byte[] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) != -1) {
                output.write(buffer, 0, length);
            }
        }
    }
}
  1. ファイルコピー時の例外処理 ===================

  2. 伝統的なアプローチ


  1. JDK7以降の改善点

  1. JDK9以降の進化

タグ: Java ファイル操作 フォルダコピー IOリソース管理 例外処理

6月20日 18:31 投稿