Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Java Development Journal

Copy a File or Directory in Java

by

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 useFiles.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, useFiles.walkFileTree method.

 

2. Copy File Using Java

We will useFiles.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 throwNoSuchFileException. Most of the time we want to Copy files from one directory to another including sub directories. We will useFiles.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 ourCustomFileVisitor

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 usingFiles.copy(), look out forStandardCopyOption.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 waysCopy 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 learnHow to create a directory in Java.

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

References

  1. Files#copy
  2. StandardCopyOption#COPY_ATTRIBUTES
  3. Files#walkFileTree
  4. Apache Commons IO#FileUtils

2 thoughts on “Copy a File or Directory in Java”

  1. Thanks so much for the nio file walker example. Its been really hard to get started with file walker but your example works very well. I’m not fully sure how it all hangs together yet but its nice to get a working example to study in detail. Many thanks again

Comments are closed.

Learning Path

Popular

About

Java Development Journal
Java Development Journal

[8]ページ先頭

©2009-2025 Movatter.jp