Java Reference
In-Depth Information
➤
Path myPath.toAbsolutePath()
: Converts a relative path to an absolute one.
➤
Path myPath.toRealPath(LinkOption... options)
: Returns the real path of an existing
ile. If
true
is passed in the
options
parameters, links will be resolved to their real paths (if
the file system supports links). In addition, relative paths will be converted to absolute ones
and redundant elements will be removed.
the Files Class
Apart from the
Path
interface, the
Files
class is the other most important class contained in the
java.nio.file
package. This utility class offers a set of static methods for reading, writing, and
manipulating files and folders (do not be thrown off by the fact that the class itself is named
Files
and not
FilesAndFolders
).
Note
Similarly to
Path
with its
Paths
helper and
FileSystem
with its
FileSystems
counterpart, you might expect
Files
to contain methods that
return
File
objects. However, the
File
class already existed before the advent
of NIO2 (you'll meet it in the legacy file section ahead), so that all methods in
the
Files
class that do return an object representing an entity in a file system
will return it as a
Path
object, not
File
.
Checking Existence
The first and most basic operation you can execute using the
Files
class is performing checks on
files and folders. Let's say you have created a
Path
object representing a file or folder. How do you
check whether this path actually exists? Two methods exist (no pun intended) to do so:
➤
boolean Files.exists(Path pathToCheck, LinkOption... options)
➤
boolean Files.notExists(Path pathToCheck, LinkOption... options)
Ignore the options parameter for now. As we've said, this parameter is there to specify how
links should be dealt with. A more interesting question is why two methods are provided.
Couldn't you just use
!Files.exists(path)
instead of
Files.notExists(path)
? The reason
for this is because—when checking the existence of a path—three results can occur: the file
exists, the file does not exist, or your program cannot determine the existence, for instance,
when access rules block your program from reaching the path. If both
exists
and
notExists
return
false
, this means the existence of the path cannot be verified. If exists returns
true
, this
means you can safely continue working with this file, as it exists and can be accessed from your
program.
There are also a number of other methods to check a file's status:
➤
boolean Files.isReadable(Path pathToCheck)
: Tests whether a path is readable.
➤
boolean Files.isWritable(Path pathToCheck)
: Tests whether a path is writable.
➤
boolean Files.isExecutable(Path pathToCheck)
: Tests whether a path is executable.
Search WWH ::
Custom Search