Copy a File or Directory in Java

Updated on February 22nd, 2018

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 following operation.

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

We will be using Java 7+ and Apache Commons API for copying a file or directory in Java.

1.  Copy Directory Using Java

We will be using 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);

    }

}

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 be using 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("/Users/umesh/personal/tutorials/source/Variation_Relations.csv");
        Path targetDirectory = Paths.get("/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.

This is not what we might want in many cases. Most of the time we want to Copy files from one directory to another in Java including sub directories.

We will be usingFiles.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

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.

follow me on:

2
Leave a Reply

avatar
0 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors

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

  Subscribe  
newest oldest most voted
Notify of