java

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.

import java.io.*;

public class Main
{
	public static void copy(File src, File dest) throws IOException{
		
    	if(src.isDirectory()){
    		//if the directory does not exist, create it
    		if(!dest.exists()){
    		   dest.mkdir();
    		   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);
    		}
    	}else{
    	    //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 = in.read(buffer)) > 0){
    	    	out.write(buffer, 0, length);
    	    }
 
    	    in.close();
    	    out.close();
    	    System.out.println("File " + src + " > " + dest);
    	}
	}

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

Output:

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 *