Monday, March 5, 2012

Java Method to copy a folder directory contents from source location to destination location


public void copyDirectory(java.io.File sourceLocation, java.io.File targetLocation) {
 System.out.println("Starting Copying");
 try {
  if (sourceLocation.isDirectory()) {
   if (!targetLocation.exists()) {
    targetLocation.mkdir();
   }

   String[] children = sourceLocation.list();
   for (int i = 0; i < children.length; i++) {
    copyDirectory(new java.io.File(sourceLocation, children[i]),
      new java.io.File(targetLocation, children[i]));
   }
  } 
  else {
   java.io.InputStream in = new java.io.FileInputStream(sourceLocation);
   java.io.OutputStream out = new java.io.FileOutputStream(targetLocation);
   byte[] buf = new byte[1024];
   int len;
   while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
   }
   in.close();
   out.close(); 
  }
 } catch (java.io.IOException e) {
  e.printStackTrace();
  throw new RuntimeException(e);
 }
 System.out.println("Completed Copying");
}

To test this method just create a directory at any location say: (c:/sourceLocation/) with some files in it. And you want to copy all the contents of this directory to a new location say : (d:/targetLocation) which may or may not exist. Then this function will create the target location and copy all the contents from the given source location to the target location. 

 The sample test class to test this method:
public class TestCopyDrectory {

 public static void main(String[] args) {
  copyDirectory(new java.io.File("C:/sourceLocation/"), new java.io.File("D:/targetLocation"));
 }

 public static void copyDirectory(java.io.File sourceLocation, java.io.File targetLocation) {
  System.out.println("Starting Copying");
  try {
   if (sourceLocation.isDirectory()) {
    if (!targetLocation.exists()) {
     targetLocation.mkdir();
    }

    String[] children = sourceLocation.list();
    for (int i = 0; i < children.length; i++) {
     copyDirectory(new java.io.File(sourceLocation, children[i]),
       new java.io.File(targetLocation, children[i]));
    }
   } 
   else {
    java.io.InputStream in = new java.io.FileInputStream(sourceLocation);
    java.io.OutputStream out = new java.io.FileOutputStream(targetLocation);
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
     out.write(buf, 0, len);
    }
    in.close();
    out.close(); 
   }
  } catch (java.io.IOException e) {
   e.printStackTrace();
   throw new RuntimeException(e);
  }
  System.out.println("Completed Copying");
 }

}