Copy Files with Parallel in Java Thread


Create new folder named from_my_files. In this folder, create 3 text files: a.txt, b.txt and c.txt

Create package demo and create new java class as below:

package demo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ParallelTasks {

	private final Collection<Runnable> tasks = new ArrayList<Runnable>();

	public void add(final Runnable task) {
		tasks.add(task);
	}

	public void go() throws InterruptedException {
		final ExecutorService threads = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
		try {
			final CountDownLatch latch = new CountDownLatch(tasks.size());
			for (final Runnable task : tasks)
				threads.execute(new Runnable() {
					public void run() {
						try {
							task.run();
						} finally {
							latch.countDown();
						}
					}
				});
			latch.await();
		} finally {
			threads.shutdown();
		}
	}

}




In demo package, create new java class as below:

package demo;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class CopyFileTask implements Runnable {

	private String fromPath;
	private final String toPath;

	public CopyFileTask(String fromPath, String toPath) {
		this.fromPath = fromPath;
		this.toPath = toPath;
	}

	@Override
	public void run() {
		try {
			Path to = Paths.get(toPath);
			Path from = Paths.get(fromPath);
			Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}

}

In demo package, create Main java class as below:

package demo;

import java.io.File;

public class Main {

	public static void main(String[] args) {

		try {
			ParallelTasks tasks = new ParallelTasks();
			File folder = new File("c:\\from_my_files");
			for (File file : folder.listFiles()) {
				tasks.add(new CopyFileTask(file.getAbsolutePath(), "c:\\to_my_files\\" + file.getName()));
			}
			tasks.go();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}

	}

}