__CONFIG_colors_palette__{"active_palette":0,"config":{"colors":{"40f3f":{"name":"Main Accent","parent":-1}},"gradients":[]},"palettes":[{"name":"Default","value":{"colors":{"40f3f":{"val":"var(--tcb-color-0)"}},"gradients":[]},"original":{"colors":{"40f3f":{"val":"rgb(127, 215, 132)","hsl":{"h":123,"s":0.52,"l":0.67,"a":1}}},"gradients":[]}}]}__CONFIG_colors_palette__

__CONFIG_colors_palette__{"active_palette":0,"config":{"colors":{"40f3f":{"name":"Main Accent","parent":-1}},"gradients":[]},"palettes":[{"name":"Default","value":{"colors":{"40f3f":{"val":"var(--tcb-color-0)"}},"gradients":[]},"original":{"colors":{"40f3f":{"val":"rgb(127, 215, 132)","hsl":{"h":123,"s":0.52,"l":0.67,"a":1}}},"gradients":[]}}]}__CONFIG_colors_palette__
Table of Contents

Copy a File or Directory in Java

Copy a file or directory in Java is a common operation. In this post, we will go through different options to perform the following operation.

  1. Copy a file from one location to another location.
  2. Copy all content of a directory from one location to another.

We will use Java 7+ and Apache Commons API for copying a file or directory in Java. NIO2 provides lots of improvements to speed up the copying process. NIO2 can use the lower-level system capabilities for better performance.

1.  Copy Directory Using Java (NIO.2 API)

We will use Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING) to copy files /directory from the source location to destination location.

public class CopyDirectory {

    public static void main(String[] args) throws IOException {

        Path sourceDirectory = Paths.get("/Users/personal/tutorials/source");
        Path targetDirectory = Paths.get("/Users/personal/tutorials/target");

        //copy source to target using Files Class
        Files.copy(sourceDirectory, targetDirectory);
    }
}

It integrates with O/S native I/O for high performance (Based on your underlying file system). This will copy source directory to target location. We need to remember following points.

  1. If target directory exists, the system will throw FileAlreadyExistsException.
  2. Use StandardCopyOption.REPLACE_EXISTING to replace target location with the source.
  3. Above method will only copy source directory but not files or subdirectories.
  4. To copy files and subdirectories, use Files.walkFileTree method.

 

2. Copy File Using Java

We will use Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING) to copy files from source location to destination location.

public class CopyFIle {

    public static void main(String[] args) throws IOException {

        Path sourceDirectory = Paths.get("https://prod-acb5.kxcdn.com/Users/umesh/personal/tutorials/source/Variation_Relations.csv");
        Path targetDirectory = Paths.get("https://prod-acb5.kxcdn.com/Users/umesh/personal/tutorials/target/Variation_Relations.csv");

        //copy source to target using Files Class
        Files.copy(sourceDirectory, targetDirectory);
    }
}

Above assume that target folder already exists, if “target” directory does not exist, the system will throw NoSuchFileException. Most of the time we want to Copy files from one directory to another including sub directories. We will use Files.walkFileTree from NIO Java7 approach to recursively copy directory and all files to another location.

Custom Directory Walker

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystemLoopException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.SKIP_SUBTREE;

public class CustomFileVisitor extends SimpleFileVisitor<Path> {

    final Path source;
    final Path target;

    public CustomFileVisitor(Path source, Path target) {
        this.source = source;
        this.target = target;
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
            throws IOException
    {      
        Path newDirectory= target.resolve(source.relativize(dir));
        try{
            Files.copy(dir,newDirectory);
        }
        catch (FileAlreadyExistsException ioException){
            //log it and move
            return SKIP_SUBTREE; // skip processing
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

       Path newFile = target.resolve(source.relativize(file));

        try{
            Files.copy(file,newFile);
        }
        catch (IOException ioException){
            //log it and move
        }

        return FileVisitResult.CONTINUE;

    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {      
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        if (exc instanceof FileSystemLoopException) {
            //log error
        } else {
            //log error
        }
        return CONTINUE;
    }
}

Time to Use our CustomFileVisitor

public class CopyFilesRecursively {

    public static void main(String[] args) throws IOException {

        Path sourceLocation= Paths.get("/Users/umesh/personal/tutorials/source");
        Path targetLocation =Paths.get("/Users/umesh/personal/tutorials/target");

        CustomFileVisitor fileVisitor = new CustomFileVisitor(sourceLocation, targetLocation);
        //You can specify your own FileVisitOption
        Files.walkFileTree(sourceLocation, fileVisitor);
    }
}

If you want to permissions file permissions while copy directories/file using Files.copy(), look out for StandardCopyOption.html#COPY_ATTRIBUTES

 

2. Copy File Using Apache Commons

Apache Commons provides more easy and clean way to copy files/directories

public class CopyDirectoryApache {

    public static void main(String[] args) throws IOException {

        File sourceLocation= new File("/Users/umesh/personal/tutorials/source");
        File targetLocation = new File("/Users/umesh/personal/tutorials/target");

        FileUtils.copyDirectory(sourceLocation, targetLocation);
 }

In this post, we learned following ways Copy a File or Directory in Java

  1. Use Files.copy for simple operation.
  2. Use custom FileVisitor to recursively copy file or directories.
  3. Use Apache Commons IO.

 

Read our other post to learn How to create a directory in Java.

All the code of this article is available Over on Github. This is a Maven-based project.

References

  1. Files#copy
  2. StandardCopyOption#COPY_ATTRIBUTES
  3. Files#walkFileTree
  4. Apache Commons IO#FileUtils
0 0 vote
Article Rating

Related Posts

Java Development Journal


Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

Subscribe
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
2
0
Would love your thoughts, please comment.x
()
x