Tuesday 4 August 2015

Copy directory in Java

The following code 'll copy the contents of a given source folder to a given destination folder.This method accepts 2 parameters,one for source folder location and another for destination folder location.
public static void copyFolder(File srcFolder, File destFolder) 
throws IOException{

 if(!srcFolder.exists()){
    System.out.println("Source folder does not exist!");
    System.exit(0);
 }
    
//If folder/directory
 if(srcFolder.isDirectory()){ 

  //If destination directory doesn't exist, create it
  if(!destFolder.exists()){
     destFolder.mkdir();
  }

  //List all the contents of source directory
  String files[] = srcFolder.list();
  for (String file : files) {
     //construct the srcFolder and destFolder file structure
     File srcFile = new File(srcFolder, file);
     File destFile = new File(destFolder, file);

     //recursive copy
     copyFolder(srcFile,destFile);
  }
 }

 //If file, then copy it
 else{

 //Use bytes stream to support all file types
  InputStream in = new FileInputStream(srcFolder);
  OutputStream out = new FileOutputStream(destFolder);
     byte[] buffer = new byte[1024];
     int length;
    
     //copy the file content in bytes
     while ((length = in.read(buffer)) > 0){
     out.write(buffer, 0, length);
     }
     in.close();
     out.close();
 }
}

No comments:

Post a Comment