Java Reference
In-Depth Information
Getting
Path
Objects from URIs
An overloaded version of
Files
static
method
get
uses a
URI
object to locate the file or
directory. A
Uniform Resource Identifier (URI)
is a more general form of the
Uniform
Resource Locators (URLs)
that are used to locate websites. For example, the URL
http:/
/www.deitel.com/
is the URL for the Deitel & Associates website. URIs for locating files
vary across operating systems. On Windows platforms, the URI
file://C:/data.txt
identifies the file
data.txt
stored in the root directory of the C: drive. On UNIX/Linux
platforms, the URI
file:/home/student/data.txt
identifies the file
data.txt
stored in the
home
directory of the user
student
.
Example: Getting File and Directory Information
Figure 15.2 prompts the user to enter a file or directory name, then uses classes
Paths
,
Path
,
Files
and
DirectoryStream
to output information about that file or directory.The
program begins by prompting the user for a file or directory (line 16). Line 19 inputs the
filename or directory name and passes it to
Paths
static
method
get
, which converts the
String
to a
Path
. Line 21 invokes
Files
static
method
exists
, which receives a
Path
and determines whether it exists (either as a file or as a directory) on disk. If the name does
not exist, control proceeds to line 49, which displays a message containing the
Path
's
String
representation followed by “
does
not
exist
.” Otherwise, lines 24-45 execute:
•
Path
method
getFileName
(line 24) gets the
String
name of the file or directory
without any location information.
•
Files
static
method
isDirectory
(line 26) receives a
Path
and returns a
bool-
ean
indicating whether that
Path
represents a directory on disk.
•
Path
method
isAbsolute
(line 28) returns a
boolean
indicating whether that
Path
represents an absolute path to a file or directory.
•
Files
static
method
getLastModifiedTime
(line 30) receives a
Path
and returns
a
FileTime
(package
java.nio.file.attribute
) indicating when the file was last
modified. The program outputs the
FileTime
's default
String
representation.
•
Files
static
method
size
(line 31) receives a
Path
and returns a
long
represent-
ing the number of bytes in the file or directory. For directories, the value returned
is platform specific.
•
Path
method
toString
(called implicitly at line 32) returns a
String
represent-
ing the
Path
.
•
Path
method
toAbsolutePath
(line 33) converts the
Path
on which it's called to
an absolute path.
If the
Path
represents a directory (line 35), lines 40-41 use
Files
static
method
new-
DirectoryStream
(lines 40-41) to get a
DirectoryStream<Path>
containing
Path
objects
for the directory's contents. Lines 43-44 display the
String
representation of each
Path
in the
DirectoryStream<Path>
. Note that
DirectoryStream
is a generic type like
Array-
List
(Section 7.16).