|
Copy Directory
The following example shows how to copy a directory from source path to target path.
|
package com.bethecoder.tutorials.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyDirectoryTest {
/**
* @param args
*/
public static void main(String[] args) {
String srcDir = "C:\\NEW";
String tgtDir = "C:\\NEW2";
copyDir(srcDir, tgtDir);
System.out.println("Directory copied successfully.");
}
public static void copyDir(String srcDir, String tgtDir) {
copyDirectory(new File(srcDir), new File(tgtDir));
}
public static void copyDirectory(File srcDirFile, File tgtDirFile) {
if (srcDirFile.isFile()) {
copyFile(srcDirFile, tgtDirFile);
} else {
//Create directory
tgtDirFile.mkdirs();
//Copy children
File [] children = srcDirFile.listFiles();
for (int i = 0 ; i < children.length ; i ++ ) {
copyDirectory(children[i], new File(tgtDirFile, children[i].getName()));
}
}
}
public static void copyFile(File srcFile, File tgtFile) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(tgtFile);
byte [] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
| |
It gives the following output,
Directory copied successfully.
|
|