How to recursively copy the entire directory, including the parent folder in Java

I am currently copying folders from one place to another. It works fine, but does not copy the source folder, in which all other files and folders are at the end. This is the code I'm using:

public static void copyFolder(File src, File dest) throws IOException { if (src.isDirectory()) { //if directory not exists, create it if (!dest.exists()) { dest.mkdir(); } //list all the directory contents String files[] = src.list(); for (String file : files) { //construct the src and dest file structure File srcFile = new File(src, file); File destFile = new File(dest+"\\"+src.getName(), file); //recursive copy copyFolder(srcFile,destFile); } } else { //if file, then copy it //Use bytes stream to support all file types InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); out.close(); System.out.println("File copied from " + src + " to " + dest); } } 

So, I have src folder C:\test\mytest\..all folders..

I want to copy it to C:\test\myfiles

But instead of getting C:\test\myfiles\mytest\..all folders.. im getting C:\test\myfiles\..all folders..

+6
source share
8 answers

There is a tutorial on copying files using java.nio with a recursive copy of the sample code in Oracle documents . It works with java se 7+. It uses the Files.walkFileTree method, which can cause some problems with ntfs with junction points . To avoid using Files.walkFileTree, a possible solution might look like this:

 public static void copyFileOrFolder(File source, File dest, CopyOption... options) throws IOException { if (source.isDirectory()) copyFolder(source, dest, options); else { ensureParentFolder(dest); copyFile(source, dest, options); } } private static void copyFolder(File source, File dest, CopyOption... options) throws IOException { if (!dest.exists()) dest.mkdirs(); File[] contents = source.listFiles(); if (contents != null) { for (File f : contents) { File newFile = new File(dest.getAbsolutePath() + File.separator + f.getName()); if (f.isDirectory()) copyFolder(f, newFile, options); else copyFile(f, newFile, options); } } } private static void copyFile(File source, File dest, CopyOption... options) throws IOException { Files.copy(source.toPath(), dest.toPath(), options); } private static void ensureParentFolder(File file) { File parent = file.getParentFile(); if (parent != null && !parent.exists()) parent.mkdirs(); } 
+3
source

You can try Apache FileUtils to copy directories as well

+1
source
+1
source

Using java.nio:

 import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; public static void copy(String sourceDir, String targetDir) throws IOException { abstract class MyFileVisitor implements FileVisitor<Path> { boolean isFirst = true; Path ptr; } MyFileVisitor copyVisitor = new MyFileVisitor() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // Move ptr forward if (!isFirst) { // .. but not for the first time since ptr is already in there Path target = ptr.resolve(dir.getName(dir.getNameCount() - 1)); ptr = target; } Files.copy(dir, ptr, StandardCopyOption.COPY_ATTRIBUTES); isFirst = false; return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path target = ptr.resolve(file.getFileName()); Files.copy(file, target, StandardCopyOption.COPY_ATTRIBUTES); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { throw exc; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Path target = ptr.getParent(); // Move ptr backwards ptr = target; return FileVisitResult.CONTINUE; } }; copyVisitor.ptr = Paths.get(targetDir); Files.walkFileTree(Paths.get(sourceDir), copyVisitor); } 
+1
source
+1
source

The main problem is as follows:

  dest.mkdir(); 

create only one directory, not the parent, and after the first step you need to create two directories, so replace mkdir with mkdirs . After that, I assume that you will have duplicate child directories due to your recursion (something like C: \ test \ myfiles \ mytest \ dir1 \ dir1 \ subdir1 \ subdir1 ...), so try to fix the following lines:

  File destFile = new File(dest, src.getName()); /**/ OutputStream out = new FileOutputStream(new File(dest, src.getName())); 
0
source

This code copies the folder from source to destination:

  public static void copyDirectory(String srcDir, String dstDir) { try { File src = new File(srcDir); String ds=new File(dstDir,src.getName()).toString(); File dst = new File(ds); if (src.isDirectory()) { if (!dst.exists()) { dst.mkdir(); } String files[] = src.list(); int filesLength = files.length; for (int i = 0; i < filesLength; i++) { String src1 = (new File(src, files[i]).toString()); String dst1 = dst.toString(); copyDirectory(src1, dst1); } } else { fileWriter(src, dst); } } catch (Exception e) { e.printStackTrace(); } } public static void fileWriter(File srcDir, File dstDir) throws IOException { try { if (!srcDir.exists()) { System.out.println(srcDir + " doesnot exist"); throw new IOException(srcDir + " doesnot exist"); } else { InputStream in = new FileInputStream(srcDir); OutputStream out = new FileOutputStream(dstDir); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } } catch (Exception e) { } } 
0
source

Source: https://habr.com/ru/post/921312/


All Articles