This quick code tip shows how to use Java NIO API to copy or move a file from one location in the file system to another.Explanation of the code
- First an instance of
java.nio.file.FileSystemis created using the
FileSystemprovides access to the underlying file system on the machine on which the JVM is running. Its role is that of factoryClick to understand the concept of factories in software design which creates the instances of classes in the
NIO APIused to access the various file system elements.
- An instance of
java.nio.file.Pathis obtained using the
Pathinstance is an encapsulation around a file or a directory in the file system. (Note – In Unix a directory is also a file;the same logic extends in Java running on Windows and a Path instance can hold a file or a directory instance on Windows as well)
Pathinstances are created. First Path instance is named
srcPath. This refers to the file named
file1.txtwhich needs to be copied/moved.
Pathinstance is named
destPath. This refers to the full path where we want to copy or move the file to and the file name with which we want it to be created (copied/moved) with in the destination folder. (Note – This is important difference from a normal file copy which is performed in Windows or Unix where using GUI or command line only the destination folder has to be provided as the name of the file which is copied/moved remains the same. However, here you need to provide the file name at the destination as well.)
- Next the actual copy/move is done by passing the
StandardCopyOptionenum constant value to the
- The class
java.nio.file.Filesprovides static methods for working with files and directories.
java.nio.file.StandardCopyOptionis an enum implementation of
java.nio.file.CopyOptioninterface which acts as a base interface for providing configurations/options for copying/moving a file.
- The following enum constants defined in
StandardCopyOptioncan be used as the third argument in the
Files.move()methods –Table: Enum Constants in StandardCopyOption
Enum Constant Purpose REPLACE_EXISTING To replace an existing file with the same name in the destination COPY_ATTRIBUTES To copy attributes to the file in the destination folder ATOMIC_MOVE To move the file as an atomic file system operation
- NOTE – In the above example I have copied
file1.txtand then moved the same file. If you change the order of these commands and first move and then copy, then copy will fail because the file would already have been moved!