Monday, October 31, 2011

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.
  1. public static void copyFolder(File srcFolder, File destFolder)  
    throws IOException{
  2.  
  3.  if(!srcFolder.exists()){
  4.     System.out.println("Source folder does not exist!");
  5.     System.exit(0);
  6.  }
  7.      
  8. //If folder/directory
  9.  if(srcFolder.isDirectory()){  
  10.  
  11.   //If destination directory doesn't exist, create it
  12.   if(!destFolder.exists()){
  13.      destFolder.mkdir();
  14.   }
  15.  
  16.   //List all the contents of source directory
  17.   String files[] = srcFolder.list();
  18.   for (String file : files) {
  19.      //construct the srcFolder and destFolder file structure
  20.      File srcFile = new File(srcFolder, file);
  21.      File destFile = new File(destFolder, file);
  22.  
  23.      //recursive copy
  24.      copyFolder(srcFile,destFile);
  25.   }
  26.  }
  27.  
  28.  //If file, then copy it
  29.  else{
  30.  
  31.  //Use bytes stream to support all file types
  32.   InputStream in = new FileInputStream(srcFolder);
  33.   OutputStream out = new FileOutputStream(destFolder);
  34.      byte[] buffer = new byte[1024];
  35.      int length;
  36.      
  37.      //copy the file content in bytes
  38.      while ((length = in.read(buffer)) > 0){
  39.      out.write(buffer, 0, length);
  40.      }
  41.      in.close();
  42.      out.close();
  43.  }
  44. }

No comments:

Post a Comment