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.
- Copy a file from one location to another location.
- 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.
- If target directory exists, the system will throw
FileAlreadyExistsException.
- Use
StandardCopyOption.REPLACE_EXISTING
to replace target location with the source. - Above method will only copy source directory but not files or subdirectories.
- 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("/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
. 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
- Use Files.copy for simple operation.
- Use custom FileVisitor to recursively copy file or directories.
- 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
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
Happy it was helpful for your Patrick!!