Copy Directory content from one directory to another directory

Copy one directory data into another directory with all file and folder using java.io package.

Example:


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyDirectory {

	public static void main(String args[]){
		File src = new File("D:\\SourceDir");
		File dest = new File("D:\\DestDir");
		try{
			copyDirectory(src,dest);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}
	
	public static void copyDirectory(File sourceLocation , 
File targetLocation) throws IOException {
	    if (sourceLocation.isDirectory()) {
	        if (!targetLocation.exists()) {
	            targetLocation.mkdir();
	        }

	        String[] children = sourceLocation.list();
	        for (int i=0; i 0) {
		          out.write(buf, 0, len);
		      }
		      in.close();
		      out.close();
	    }
	}
}


 

If destination directory is not exist than above code will create destination directory first and then copy, but if source directory is not exist than code will throw FileNotFoundException.