How to copy one directory to another directory in java?

Below is the code snippet of method to copy one directory to another directory. The method accepts two arguments one is source directory and another is target directory. This method copies the subdirectories and subfiles recursively as shown below.


public static void copyDirectory(File sourceDir , File targetDir) throws IOException {

if (sourceDir.isDirectory()) {
if (!targetDir.exists()) {
targetDir.mkdir();
}

String[] childFiles = sourceDir.list();
for (int i=0; i copyDirectory(new File(sourceDir, childFiles[i]), new File(targetDir, childFiles[i]));
}
} else {

InputStream in = new FileInputStream(sourceDir);
OutputStream out = new FileOutputStream(targetDir);

// Instream to OutputStream bit copying
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment