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:

Path sourceFile = Paths.get("NioVideo.mp4");
Path targetFile = Paths.get("e:\\Java\\JavaSE\\NIO\\NioVideo.mp4");

try {

	Files.copy(sourceFile, targetFile,
		StandardCopyOption.REPLACE_EXISTING);

} catch (IOException ex) {
	System.err.format("I/O Error when copying file");
}


The following code opens a web page and saves it to a file:

Path targetFile = Paths.get("Google.html");

URI uri = URI.create("http://google.com");

try (InputStream inputStream = uri.toURL().openStream()) {
	Files.copy(inputStream, targetFile);
} catch (IOException ex) {
	System.err.format("I/O Error when copying file");
}
And more generally, the following program copies a file to another directory, with the file and directory are supplied from command-line arguments:

import java.io.*;
import java.nio.file.*;

/**
 * This program copies a file to another directory using the Java NIO API.
 *
 * @author www.codejava.net
 */
public class CopyFile {

	public static void copyFile(String filePath, String dir) {
		Path sourceFile = Paths.get(filePath);
		Path targetDir = Paths.get(dir);
		Path targetFile = targetDir.resolve(sourceFile.getFileName());

		try {

			Files.copy(sourceFile, targetFile);

		} catch (FileAlreadyExistsException ex) {
			System.err.format("File %s already exists.", targetFile);
		} catch (IOException ex) {
			System.err.format("I/O Error when copying file");
		}
	}

	public static void main(String[] args) {
		String filePath = args[0];
		String dir = args[1];

		copyFile(filePath, dir);
	}
}
Run this program like this:

java CopyFile <sourceFile> <targetDir>
For example:

java CopyDir "e:\Java\JavaSE\NIO\Tutorial.html" "F:\Archive\Java”
 

3. Copying a Directory Example

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));
	}
}
Run this program like this:

java CopyDir <sourceDir> <targetDir>
For example:

java CopyDir "e:\Java\JavaSE\Swing" "F:\Archive”
 

API References:

 

Related File IO Tutorials:

 

Other Java File IO Tutorials:


About the Author:

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.



Add comment

   


Comments 

#1Luigi Casiello2022-08-10 04:52
Thank you very much!
Your sample is perfect, i have replaced in my code the old "Files.copy" from java.util.
Quote