/** * Copies a directory from one path to another. If the destination directory exists, the file * contents are merged and files from the source directory overwrite files in the destination. */ public static void copyDirectory(@NonNull File from, @NonNull File to) throws IOException { Preconditions.checkArgument(from.isDirectory(), "Source path is not a directory."); Preconditions.checkArgument( !to.exists() || to.isDirectory(), "Destination path exists and is not a directory."); mkdirs(to); File[] children = from.listFiles(); if (children != null) { for (File child : children) { if (child.isFile()) { copyFileToDirectory(child, to); } else if (child.isDirectory()) { copyDirectoryToDirectory(child, to); } else { throw new IllegalArgumentException( "Don't know how to copy file " + child.getAbsolutePath()); } } } }
/** * Makes a copy of the directory's content, in the specified location, while maintaining the * directory structure. So the entire directory tree from the source will be copied. * * @param from directory from which the content is copied * @param to destination directory, will be created if does not exist */ public static void copyDirectoryContentToDirectory( @NonNull final File from, @NonNull final File to) throws IOException { Preconditions.checkArgument(from.isDirectory(), "Source path is not a directory."); File[] children = from.listFiles(); if (children != null) { for (File f : children) { if (f.isDirectory()) { File destination = new File(to, relativePath(f, from)); Files.createParentDirs(destination); mkdirs(destination); copyDirectoryContentToDirectory(f, destination); } else if (f.isFile()) { File destination = new File(to, relativePath(f.getParentFile(), from)); Files.createParentDirs(destination); mkdirs(destination); copyFileToDirectory(f, destination); } } } }