Как скопировать папку и все ее подпапки и файлы в другую папку?
Как скопировать папку и все ее подпапки и файлы в другую папку
Ответ 1
Apo Commons IO может сделать трюк для вас. Посмотрите FileUtils.
Ответ 2
Выберите, что вам нравится:
- FileUtils от Apache Commons IO (самый простой и безопасный способ)
Пример с FileUtils:
File srcDir = new File("C:/Demo/source");
File destDir = new File("C:/Demo/target");
FileUtils.copyDirectory(srcDir, destDir);
- Вручную, пример до Java 7 (CHANGE: закрыть потоки в блоке finally)
- Вручную, Java >= 7
Пример с функцией AutoCloseable в Java 7:
public void copy(File sourceLocation, File targetLocation) throws IOException {
if (sourceLocation.isDirectory()) {
copyDirectory(sourceLocation, targetLocation);
} else {
copyFile(sourceLocation, targetLocation);
}
}
private void copyDirectory(File source, File target) throws IOException {
if (!target.exists()) {
target.mkdir();
}
for (String f : source.list()) {
copy(new File(source, f), new File(target, f));
}
}
private void copyFile(File source, File target) throws IOException {
try (
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)
) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
}
}
Ответ 3
посмотрите на java.io.File для кучи функций.
вы выполните итерацию по существующей структуре и mkdir, сохраните и т.д., чтобы получить глубокую копию.
Ответ 4
JAVA NIO поможет вам решить вашу проблему. Пожалуйста, взгляните на это http://tutorials.jenkov.com/java-nio/files.html#overwriting-existing-files.