Last Updated on 28 July 2019   |   Print Email
This Java tutorial guides you how to copy a file or copy a whole directory (including sub files and sub directories) using the Java NIO API.
1. The File Copy Methods
The java.nio.file.Files helper class provides three different utility methods for copying a file:
long copy(InputStream in, Path target, CopyOption... options): copies all bytes from an input stream to a file, and returns the number of bytes read or written. This method is ideal if you have an InputStream already opened.
long copy(Path source, OutputStream out): copies all bytes from a file to an output stream, and returns the number of bytes read or written. This method is ideal if you have an OutputStream already opened.
Path copy(Path source, Path target, CopyOption... options): copies a file to a target file, and returns the path to the target file. This method is ideal for most use cases.
If the source is a directory, then only the directory is created even when the original directory contains files.The optional parameter CopyOption specifying how the copy should be done. Use the enums StandardCopyOption and LinkOption for this parameter with the following values:
COPY_ATTRIBUTES: copy attributes to the new file, e.g. last-modified-time attribute.
REPLACE_EXISTING: replace an existing file if it exists.
NOFOLLOW_LINKS: If a file is a symbolic link, then the link itself, not the target of the link, is copied.
If the copy option is not specified, then the copy fails if the target file already exists or is a symbolic link.These copy methods can throw the following checked exceptions:
FileAlreadyExistsException: if the target file already exists but it cannot be replaced because the REPLACE_EXISTING option is not specified.
DirectoryNotEmptyException: if the target file cannot be replaced because it is a non-empty directory (when the REPLACE_EXISTING option is specified).
IOException: if an I/O error occurs when reading or writing.
UnsupportedOperationException: if the options contain an option that is not supported.
SecurityException: if the user doesn’t have read/write permission.
2. Copying Files Examples
The following code copies a video file from the current directory (relative path) to another directory (absolute path) and replaces the target file if exists:
The copy methods cannot copy a non-empty directory. If you attempt to copy a non-empty directory using the copy methods, only the name of the target directory is created, not its sub files and directories.The Java NIO API provides an easy and convenient way for copying all sub files and sub directories in a directory recursively, using the Walk File Tree API. The following simple program copies a whole directory (including its sub files and directories) to another one:
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
/**
* This program copies a whole directory (including its sub files and
* sub directories) to another, using the Java NIO API.
*
* @author www.codejava.net
*/
public class CopyDir extends SimpleFileVisitor<Path> {
private Path sourceDir;
private Path targetDir;
public CopyDir(Path sourceDir, Path targetDir) {
this.sourceDir = sourceDir;
this.targetDir = targetDir;
}
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attributes) {
try {
Path targetFile = targetDir.resolve(sourceDir.relativize(file));
Files.copy(file, targetFile);
} catch (IOException ex) {
System.err.println(ex);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attributes) {
try {
Path newDir = targetDir.resolve(sourceDir.relativize(dir));
Files.createDirectory(newDir);
} catch (IOException ex) {
System.err.println(ex);
}
return FileVisitResult.CONTINUE;
}
public static void main(String[] args) throws IOException {
Path sourceDir = Paths.get(args[0]);
Path targetDir = Paths.get(args[1]);
Files.walkFileTree(sourceDir, new CopyDir(sourceDir, targetDir));
}
}
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments
Your sample is perfect, i have replaced in my code the old "Files.copy" from java.util.