FileUtils.copyDirectory()

Copies a whole directory to a new location preserving the file dates. This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.

The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.

To do so, here's the example code

String source = "C:/your/source";
File srcDir = new File(source);

String destination = "C:/your/destination";
File destDir = new File(destination);

try {
    FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
    e.printStackTrace();
}
Answer from Jigar Joshi on Stack Overflow
Top answer
1 of 9
127

FileUtils.copyDirectory()

Copies a whole directory to a new location preserving the file dates. This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.

The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.

To do so, here's the example code

String source = "C:/your/source";
File srcDir = new File(source);

String destination = "C:/your/destination";
File destDir = new File(destination);

try {
    FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
    e.printStackTrace();
}
2 of 9
34

The following is an example of using JDK7.

public class CopyFileVisitor extends SimpleFileVisitor<Path> {
    private final Path targetPath;
    private Path sourcePath = null;
    public CopyFileVisitor(Path targetPath) {
        this.targetPath = targetPath;
    }

    @Override
    public FileVisitResult preVisitDirectory(final Path dir,
    final BasicFileAttributes attrs) throws IOException {
        if (sourcePath == null) {
            sourcePath = dir;
        } else {
        Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(final Path file,
    final BasicFileAttributes attrs) throws IOException {
    Files.copy(file,
        targetPath.resolve(sourcePath.relativize(file)));
    return FileVisitResult.CONTINUE;
    }
}

To use the visitor do the following

Files.walkFileTree(sourcePath, new CopyFileVisitor(targetPath));

If you'd rather just inline everything (not too efficient if you use it often, but good for quickies)

    final Path targetPath = // target
    final Path sourcePath = // source
    Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(final Path dir,
                final BasicFileAttributes attrs) throws IOException {
            Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(final Path file,
                final BasicFileAttributes attrs) throws IOException {
            Files.copy(file,
                    targetPath.resolve(sourcePath.relativize(file)));
            return FileVisitResult.CONTINUE;
        }
    });
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ copy a directory in java
Copy a Directory in Java | Baeldung
January 8, 2024 - Java NIO has been available since Java 1.4. Java 7 introduced NIO 2 that brought a lot of useful features like better support for handling symbolic links, file attributes access. It also provided us with classes such as Path, Paths, and Files that made file system manipulation much easier. ... public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException { Files.walk(Paths.get(sourceDirectoryLocation)) .forEach(source -> { Path destination = Paths.get(destinationDirectoryLocation, source.toString() .substring(sourceDirectoryLocation.length())); try { Files.copy(source, destination); } catch (IOException e) { e.printStackTrace(); } }); }
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ tutorial โ€บ essential โ€บ io โ€บ copy.html
Copying a File or Directory (The Javaโ„ข Tutorials > Essential Java Classes > Basic I/O)
See Java Language Changes for a ... removed or deprecated options for all JDK releases. You can copy a file or directory by using the copy(Path, Path, CopyOption...) method....
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ javas-files-copy-method-explained-aba9aeb73486
Javaโ€™s Files.copy() Method Explained | Medium
January 12, 2025 - At its core, Files.copy() performs a copy operation by reading the source file or directory and writing its contents to the target location. The methodโ€™s behavior can be customized through optional arguments, allowing developers to specify ...
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ i/o โ€บ copying a directory in java
Copying a Directory in Java
October 1, 2022 - If the destination directory did exist, then this method merges the source with the destination. The copyDirectory() is an overloaded method with the following parameters:
๐ŸŒ
Dev.java
dev.java โ€บ learn โ€บ java-io โ€บ file-system โ€บ move-copy-delete
Manipulating Files and Directories - Dev.java
January 25, 2023 - The copy(InputStream, Path, CopyOptions...) method may be used to copy all bytes from an input stream to a file. The copy(Path, OutputStream) method may be used to copy all bytes from a file to an output stream.
Find elsewhere
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ how to copy directory in java
How to copy directory in Java - Mkyong.com
July 28, 2020 - Create directories : /home/mkyong/test2 Copy File from '/home/mkyong/test/test-a2.log' to '/home/mkyong/test2/test-a2.log' Copy File from '/home/mkyong/test/test-a1.log' to '/home/mkyong/test2/test-a1.log' Create directories : /home/mkyong/test2/test-b Copy File from '/home/mkyong/test/test-b/test-b1.txt' to '/home/mkyong/test2/test-b/test-b1.txt' Create directories : /home/mkyong/test2/test-b/test-c Copy File from '/home/mkyong/test/test-b/test-c/test-c2.log' to '/home/mkyong/test2/test-b/test-c/test-c2.log' Copy File from '/home/mkyong/test/test-b/test-c/test-c1.log' to '/home/mkyong/test2/t
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2016 โ€บ 02 โ€บ how-to-copy-non-empty-directory-in-java.html
How to Copy Non Empty Directory with Files in Java- Example Tutorial
May 7, 2023 - In order to copy a file or a directory in JDK 1.7, simply calling Files.copy(fromPath, toPath) is enough, but it will only work if the source directory is not empty. In order to copy a directory with files and subdirectories, you need to write ...
๐ŸŒ
Java Development Journal
javadevjournal.com โ€บ home โ€บ copy a file or directory in java
Copy a File or Directory in Java | Java Development Journal
June 29, 2020 - Learn to copy a file or directory in Java. Learn how to copy all files or folders recursively in Java using Java NIO and Apache Commons IO.
๐ŸŒ
DZone
dzone.com โ€บ coding โ€บ java โ€บ how to copy files from one directory to another in java: example
Copy Files From One Directory to Another in Java
October 23, 2021 - It also copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method will overwrite it. ... import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; /** * Java program to copy a file from one directory to another e.g.
๐ŸŒ
Kodejava
kodejava.org โ€บ how-do-i-copy-directory-with-all-its-contents-to-another-directory
How do I copy directory with all its contents to another directory? - Learn Java by Examples
To copy a directory with the entire child directories and files we can use a handy method provided by the Apache Commons IO FileUtils.copyDirectory(). This method accepts two parameters, the source directory and the destination directory. The source directory should be available while if the destination directory doesnโ€™t exist, it will be created. package org.kodejava.commons.io; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; public class DirectoryCopy { public static void main(String[] args) { // An existing directory to copy.
๐ŸŒ
Attacomsian
attacomsian.com โ€บ blog โ€บ java-copy-files-from-one-directory-to-another
How to copy files from one directory to another in Java
December 15, 2019 - try { // source & destination directories Path src = Paths.get("dir"); Path dest = Paths.get("dir-new"); // create stream for `src` Stream<Path> files = Files.walk(src); // copy all files and folders from `src` to `dest` files.forEach(file -> { try { Files.copy(file, dest.resolve(src.relativize(file)), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } }); // close the stream files.close(); } catch (IOException ex) { ex.printStackTrace(); }
๐ŸŒ
Medium
34codefactory.medium.com โ€บ java-how-to-copy-directories-recursively-code-factory-9cc0d6dfb7da
Java โ€” How to copy Directories recursively | Code Factory | by Code Factory | Medium
July 20, 2020 - package com.example.java.programming.file;import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption;/** * @author code.factory * */ public class CopyDirectoryRecursively { public static void main(String... args) throws IOException { Path sourceDir = Paths.get("folder/folder1"); Path destinationDir = Paths.get("folder/folder2"); // Traverse the file tree and copy each file/directory.
๐ŸŒ
Java67
java67.com โ€บ 2020 โ€บ 04 โ€บ how-to-recursive-copy-directory-in-java.html
How to recursive copy directory in Java with sub-directories and files? Example | Java67
In order to copy the whole directory with all its sub-directories and files, you need to recursively copy each item unless you reach the top of the directory. When copying a symbolic link, the target of the link is copied. If you want to copy the link itself, and not the contents of the link, specify either the NOFOLLOW_LINKS or REPLACE_EXISTING option. The following Java code shows how to use the copy method: import static java.nio.file.StandardCopyOption.*; ...
๐ŸŒ
CodeJava
codejava.net โ€บ java-se โ€บ file-io โ€บ how-to-copy-a-directory-programmatically-in-java
How to copy a directory programmatically in Java
* @author www.codejava.net * */ public class CopyDirectoryTest { public static void main(String[] args) { File sourceDir = new File("E:/TestCopy"); File destDir = new File("D:/Copy"); try { CopyUtil.copyDirectory(sourceDir, destDir); } catch (IOException ex) { ex.printStackTrace(); } } }This program will copy content of the directory E:/TestCopy to the directory D:/Copy, supposing the E:/TestCopy directory has the following structure: Then the test program will output the following: Calculate total files, sub directories and size of a directory ... Nam Ha Minh is certified Java programmer (SCJP and SCWCD).
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-copy-file
Java Copy File - 4 Ways to Copy File in Java | DigitalOcean
August 3, 2022 - This is the conventional way of file copy in java. Here we create two Files - source and destination. Then we create InputStream from source and write it to the destination file using OutputStream for java copy file operation.
๐ŸŒ
CalliCoder
callicoder.com โ€บ java-copy-file
How to copy a File or Directory in Java | CalliCoder
February 18, 2022 - In this article, youโ€™ll learn how to copy a file or directory in Java using various methods like Files.copy() or using BufferedInputStream and BufferedOutputStream.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ how to copy a file with java
How to Copy a File with Java | Baeldung
January 4, 2024 - The NIO.2 Files class provides a set of overloaded copy() methods for copying files and directories within the file system.