How to copy a directory from one location to another location? – Java

I found requirement of moving contents of one directory to another directory while cloning one object which have some associated files. Code below solves this problem using recursion, by calling same function in case the file is another directory. It is copying whole directory structure from source to target.

Code below is quite simple to understand:

 
 
// If targetLocation does not exist, it will be created.
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();
    }
}
 
 

Most Commented Posts

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)