Java NIO.2 and the class java.nio.file.Files provide useful ways of copying files. The example code shown demonstrates copying text files.
The first thing is to create Path objects for our files of interest. A Path being “an object that may be used to locate a file in a file system”.
final String BASEPATH = "C:/junk"; Path source = FileSystems.getDefault().getPath(BASEPATH, "gash.txt"); Path dest = FileSystems.getDefault().getPath(BASEPATH, "gash99.txt");
An alternate way of creating Path objects is to use the java.nio.file.Paths class. ie:
Path source = Paths.get(BASEPATH, "gash.txt"); Path dest = Paths.get(BASEPATH, "gash99.txt");
The file is copied with the statement:
With this syntax, you should see the FileAlreadyExistsException exception being thrown if the file you’re copying to already exists.
This is an “exception thrown when an attempt is made to create a file or directory and a file of that name already exists “. This action may be what you want. But if you wish to copy the file regardless, then use the options parameter of this method.
StandardCopyOption opts =
Files.copy(source, dest, opts);
- REPLACE_EXISTING – Replace an existing file if it exists.
- COPY_ATTRIBUTES – Copy attributes to the new file.
The array opts contains all of our options for the copy operation. Admittedly, this is a long-winded way of writing the statement. A shorter way would be to use a static import construct of java.nio.file.StandardCopyOption. Once the static members have been imported, they may be used without qualification:
import static java.nio.file.StandardCopyOption.*;
Files.copy(source, dest, COPY_ATTRIBUTES, REPLACE_EXISTING);
There are two ways of creating Path objects. Both achieve the same result but the former is a shorter way of doing this than the latter.
- Path source = Paths.get(BASEPATH, “gash.java”);
- Path source = FileSystems.getDefault().getPath(BASEPATH, “gash.txt”);
The classes mentioned above can be found in the java.nio.file package.
The Java Tutorials File I/O (Featuring NIO.2)
The Java Tutorials Copying a File or Directory
The Java Tutorials home page. The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. They include hundreds of complete, working examples, and dozens of lessons. Groups of related lessons are organized into “trails”.