Java Reference
In-Depth Information
• Hypothetical (may not exist yet, or may have been deleted)
g
d O
e
It is therefore fundamentally different to a File . In particular, the system depend‐
ency is manifested by Path being an interface, not a class. This enables different file‐
system providers to each implement the Path interface, and provide for system-
specific features while retaining the overall abstraction.
The elements of a Path consist of an optional root component, which identifies the
filesystem hierarchy that this instance belongs to. Note that, for example, relative
Path instances may not have a root component. In addition to the root, all Path
instances have zero or more directory names and a name element.
The name element is the element farthest from the root of the directory hierarchy
and represents the name of the file or directory. The Path can be thought of consist‐
ing of the path elements joined together by a special separator or delimiter.
Path is an abstract concept; it isn't necessarily bound to any physical file path. This
allows us to talk easily about the locations of files that don't exist yet. Java ships with
a Paths class that provides factory methods for creating Path instances.
Paths provides two get() methods for creating Path objects. The usual version
takes a String , and uses the default filesystem provider. The URI version takes
advantage of the ability of NIO.2 to plug in additional providers of bespoke filesys‐
tems. This is an advanced usage, and interested developers should consult the pri‐
mary documentation:
Path p = Paths . get ( "/Users/ben/cluster.txt" );
Path p = Paths . get ( new URI ( "file:///Users/ben/cluster.txt" ));
System . out . println ( p2 . equals ( p ));
File f = p . toFile ();
System . out . println ( f . isDirectory ());
Path p3 = f . toPath ();
System . out . println ( p3 . equals ( p ));
This example also shows the easy interoperation between Path and File objects.
The addition of a toFile() method to Path and a toPath() method to File allows
the developer to move effortlessly between the two APIs and allows for a straight‐
forward approach to refactoring the internals of code based on File to use Path
instead.
We can also make use of some useful “bridge” methods that the Files class also
provides. These provide convenient access to the older I/O APIs—for example, by
providing convenience methods to open Writer objects to specified Path locations:
Path logFile = Paths . get ( "/tmp/app.log" );
try ( BufferedWriter writer =
Files . newBufferedWriter ( logFile , StandardCharsets . UTF_8 ,
StandardOpenOption . WRITE )) {
writer . write ( "Hello World!" );
// ...
Search WWH ::




Custom Search