通过RecursiveAction复制文件

public class MoveFiles extends RecursiveAction {
    private File path;
    /**
     * 源文件夹
     */
    static String SOURCE_URL = "G:\\workspaces2";
    /**
     * 目标文件夹
     */
    static String TARGET_URL = "H:\\test";


    public MoveFiles(File path) {
        this.path = path;
    }

    @Override
    protected void compute() {
        List<MoveFiles> subTasks = new ArrayList<>();

        File[] files = path.listFiles();
        if (files != null) {
            for (File file : files) {
                String absolutePath = file.getAbsolutePath();
                String targetDir = absolutePath.replace(SOURCE_URL, TARGET_URL);
                File targetPath = new File(targetDir);
                if (file.isDirectory()) {
                    targetPath.mkdirs();
                    subTasks.add(new MoveFiles(file));
                } else {
                    try {
                        Files.copy(file.toPath(), targetPath.toPath());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (!subTasks.isEmpty()) {
                for (MoveFiles subTask : invokeAll(subTasks)) {
                    subTask.join();
                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            ForkJoinPool pool = new ForkJoinPool();
            MoveFiles task = new MoveFiles(new File(SOURCE_URL));
            pool.execute(task);
            long start = System.currentTimeMillis();
            System.out.println("任务开始");
            task.join();
            long end = System.currentTimeMillis();
            System.out.println("任务结束,耗时:" + (end - start) / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

大军
847 声望183 粉丝

学而不思则罔,思而不学则殆


下一篇 »
spring系列