Below
snippet copy contents of one directory to another.
private
static void cpFolder(File source, File destination) throws IOException {
if (!source.isDirectory()) {
copyFile(source, destination);
return;
}
if (!destination.exists()) {
destination.mkdirs();
}
String files[] = source.list();
for (String file : files) {
File srcFile = new
File(source, file);
File destFile = new
File(destination, file);
cpFolder(srcFile, destFile);
}
}
App.java
package com.sample.app; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class App { public static void copyFolder(File source, File destination) throws IOException { if (!source.isDirectory() || !source.exists()) { return; } cpFolder(source, destination); } private static void cpFolder(File source, File destination) throws IOException { if (!source.isDirectory()) { copyFile(source, destination); return; } if (!destination.exists()) { destination.mkdirs(); } String files[] = source.list(); for (String file : files) { File srcFile = new File(source, file); File destFile = new File(destination, file); cpFolder(srcFile, destFile); } } private static void copyFile(File source, File dest) throws IOException { try (InputStream inputStream = new FileInputStream(source); OutputStream outputStream = new FileOutputStream(dest);) { byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } } } public static void main(String args[]) throws IOException { File source = new File("/Users/krishna/Documents/TechnicalDocuments/ "); File destination = new File("/Users/krishna/Documents/TechnicalDocuments_copy"); copyFolder(source, destination); } }
You may
like
No comments:
Post a Comment