Thursday, April 19, 2012

Java: Copy Directory structure

Here is the code for copying a directory structure
 public static void copyFolder(String srcFile, String destFile) throws IOException
 {
  File src = new File(srcFile);
  File dest = new File(destFile);
  
  if(!src.exists())
  {
   System.out.println("Source folder do not exists [" + srcFile + "]");
   return;
  }
  
  if(src.isDirectory())
  {
    //if directory not exists, create it
    if(!dest.exists())
    {
       dest.mkdir();
    }

    //list all the directory contents
    String files[] = src.list();

    for (String file : files) 
    {
     
     //construct the src and dest file structure
     String sourceFile = src.getAbsolutePath() + File.separator + file;
     String destinationFile = dest.getAbsolutePath() + File.separator + file;
     
     //recursive copy
     copyFolder(sourceFile, destinationFile);    }
  }
  else
  {
    //if file, then copy it
    //Use bytes stream to support all file types
    InputStream in = new FileInputStream(src);
          OutputStream out = new FileOutputStream(dest); 

          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: