Java Reference
In-Depth Information
How It Works
In the new NIO.2 libraries, Java works with an abstraction level that allows for more
direct manipulation of file attributes belonging to the underlying operating system.
FileSystem.getDefaults()
gets the usable abstract system that you can do
file operations on. For example, running this example in Windows will get you a
Win-
dowsFileSystem
; if you were running this example in Linux, a
LinuxFileSys-
tem
object would be returned.
AllFileSystems
supports basic operations; in addi-
tion, each concrete
FileSystem
provides access to the unique features offered for
that operating system.
After getting the default
FileSystem
object, you can query for file objects. In
the NIO.2 file, folders and links are all called
paths
. Once you get a path, you can per-
form operations with it. In this example,
Files.copy
is called with the source and
destination paths. The last parameter refers to the different copy options. The different
copy options are file-system dependent so make sure that the one that you choose is
compatible with the operating system you intend to run the application in.
8-7. Moving a File
Problem
You need to move a file from one file system location to another.
Solution
As in Recipe 8-6, you use the default
FileSystem
to create the “to” and “from”
paths, and invoke the
Files.move() static
method:
FileSystem fileSystem = FileSystems.getDefault();
Path sourcePath = fileSystem.getPath("file.log");
Path targetPath = fileSystem.getPath("file2.log");
System.out.println("Copy from
"+sourcePath.toAbsolutePath().toString()+
" to
"+targetPath.toAbsolutePath().toString());