Pages

Wednesday, November 10, 2010

CopyDirectory Function in Java

The following function will help you copy a directory from one location to an other.I got this good function with the help of my friend google :)


public void copyDirectory(File sourceLocation , File targetLocation)
   throws IOException {
       
       if (sourceLocation.isDirectory()) {
           if (!targetLocation.exists()) {
               targetLocation.mkdir();
           }
           
           String[] children = sourceLocation.list();
           for (int i=0; i<children.length; i++) {
               copyDirectory(new File(sourceLocation, children[i]),
                       new File(targetLocation, children[i]));
           }
       } else {
           
           InputStream in = new FileInputStream(sourceLocation);
           OutputStream out = new FileOutputStream(targetLocation);
           
           // Copy the bits from instream to outstream
           byte[] buf = new byte[1024];
           int len;
           while ((len = in.read(buf)) > 0) {
               out.write(buf, 0, len);
           }
           in.close();
           out.close();
       }
   }

Usage:

                File source=new File("c:\\ak");
File target=new File("c:\\bk");
try {
copyDirectory(source,target);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Hope this helps :)

No comments:

Post a Comment