How to Copy a Directory in Java

In this tutorial, we are going to see how to copy a directory, its subdirectories, and files, into a destination directory in Java.

Java Program to Copy a Directory:

The following code will copy the “c:\\old” directory and its subdirectories and files to another “c:\\new” directory.


public class Main
	public static void copy(File src, File dest) throws IOException{
    		//if the directory does not exist, create it
    		   System.out.println("Directory "+ src + "  > " + dest);

    		//list the contents of the directory
    		String files[] = src.list();
    		for (String f : files) {
    		   //build the structure of the src and dest files
    		   File srcF = new File(src, f);
    		   File destF = new File(dest, f);
    		   //recursive copy
    		   copy(srcF, destF);
    	    //if src is a file, copy it.
    	    InputStream in = new FileInputStream(src);
    	    OutputStream out = new FileOutputStream(dest); 
    	    byte[] buffer = new byte[1024];

    	    int length;
    	    //copy the contents of the file
    	    while ((length = > 0){
    	    	out.write(buffer, 0, length);
    	    System.out.println("File " + src + " > " + dest);

    public static void main(String[] args)
    	File src = new File("c:\\old");
    	File dest = new File("c:\\new");   	
        	copy(src, dest);
        }catch(IOException e){


Directory c:\old\myFolder > c:\new\myFolder
File c:\old\myFolder\file.pdf > c:\new\myFolder\file.pdf
File c:\old\myFolder\image.png > c:\new\myFolder\image.png
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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