Sunday, August 19, 2007

How to copy a directory from one location to another location

This Java tip demonstrates a method of copying a directory from one location to another. Copying is done from sourcedirectory to targetdirectory.

// If targetLocation does not exist, it will be created.
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {

if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {

String[] children = sourceLocation.list();
for (int i=0; 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 = > 0) {
out.write(buf, 0, len);


No comments: