Copy Directory Java Recursively

In below sample java class you will see how to copy directory recursively. This examples copies all file which is inside directory and sub directories.

  • Using pure Java approach :
package com.javahonk;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class CopyDirectory {	

	public static void main(String[] args) {		
		
		try {
			File sourceDirectory =  new File("C:\\JavaHonk\\zip\\SpringMVCRESTFulService");
			File destinationDirectory =  new File("C:\\JavaHonk\\zip\\SpringMVCRESTFulServiceCopy");
			copyFolderRecursively(sourceDirectory, destinationDirectory);
			System.out.println("Dirctory copied successfully to desination: "+destinationDirectory.getAbsolutePath());
		} catch (Exception e) {
			e.printStackTrace();
		}		
		
	}

	private static void copyFolderRecursively(File sourceDirectory, File destinationDirectory) throws Exception {
		
		if (!sourceDirectory.exists()) {
			throw new Exception(("Source directory not exists:" +sourceDirectory.getAbsolutePath()));
		}
		
		if (!sourceDirectory.isDirectory()) {
			throw new Exception(("Source directory is not directory:" +sourceDirectory.getAbsolutePath()));
		}
		
		if (destinationDirectory.exists()) {
			throw new Exception(("Destination directory already exists:" +sourceDirectory.getAbsolutePath()));
		}else {
			destinationDirectory.mkdirs();
			File[] files = sourceDirectory.listFiles();
		    
		    for( File file : files ) {
		      if( file.isDirectory() ) {
		    	  copyFolderRecursively( file, new File( destinationDirectory, file.getName()));
		      } else {
		        copyFileToDestination( file, new File( destinationDirectory, file.getName() ) );
		      }
		    }
		}
		
	}
	
	private static final void copyFileToDestination(File sourceFile, File destinationFile) throws IOException {

		Files.copy(sourceFile.toPath(), destinationFile.toPath());
	}
}
  • Output:

Copy Directory Java Recursively

  • Copy directory using Apache commons (Preferred approach). Include commons-io-x.x.jar in your class path:
package com.javahonk;

import java.io.File;

import org.apache.commons.io.FileUtils;

public class CopyDirectoryUsingApacheCommon {

	public static void main(String[] args) {		
		
		try {
			
			File sourceDirectory =  new File("C:\\JavaHonk\\zip\\SpringMVCRESTFulService");
			File destinationDirectory =  new File("C:\\JavaHonk\\zip\\SpringMVCRESTFulServiceCopy");
			
			FileUtils.copyDirectory(sourceDirectory, destinationDirectory);
			
			System.out.println("Dirctory copied successfully to desination: "+destinationDirectory.getAbsolutePath());
			
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}	

}
  • Output:

Copy Directory Java Recursively

For more information about copy directory please refer oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *