Java Reference
In-Depth Information
Obtaining File Attributes
To determine whether a
Path
object references a file or a directory, you can use the static
isDirectory()
and
isRegularFile()
methods in the
Files
class. With both methods the first argument is the
Path
object
you are interested in. You can specify
NOFOLLOW_LINKS
as the optional second argument if you do not want
links to be followed.
You can also query the attributes of a file by calling the static
readAttributes()
method that is defined
in the
Files
class with the Path object specifying the file:
try{
BasicFileAttributes attr = Files.readAttributes(path,
BasicFileAttributes.class);
}catch(IOException e) {
System.err.println(e);
}
The second argument to the method is the class type for the attributes you require. Here, the attributes
are returned as a reference to an object of type
BasicFileAttributes
that contains attributes common
to most file systems. You also have the possibility of being more specific by specifying
PosixFilesAt-
tributes.class
or
DosFileAttributes.class
. All these are interface types defined in the
java.nio.file.attribute
package. You can optionally specify
NOFOLLOW_LINKS
as the third argument if
you do not want symbolic links to be followed. The method throws an
UnsupportedOperationException
if the attributes type is not supported and an
IOException
if an I/O error occurs.
information about a directory or file path:
METHODS DESCRIPTION
isDirectory()
Returns
true
if the
path
references a directory.
isRegularFile()
Returns
true
if the
path
references a regular file.
isSymbolicLink()
Returns
true
if the
path
references a symbolic link.
isOther()
Returns
true
if the
path
references something other than a regular file, a directory, or a sym-
bolic link.
creationTime()
Returns a
FileTime
object specifying the time the file was created.
lastAccessTime()
Returns a
FileTime
object specifying the time the file was last accessed.
lastModifiedTime()
Returns a
FileTime
object specifying the time the file was last modified.
size()
Returns the size of the file in bytes as a value of type
long
.
Returns a reference of type
Object
to a key that uniquely identifies the file or
null
if a key is
not available.
fileKey()
A
java.nio.file.attribute.FileTime
object is a timestamp value for a file. You can use its
toString()
method to get a string representation of its value.
To see how some of these methods go together, you can try a simple example.
TRY IT OUT: Testing a Path for a File or Directory
Try the following source code: