Java Reference
In-Depth Information
file attributes, you have the
BasicFileAttributes
and
BasicFileAtrributeView
interfaces. The
XxxAttributes
lets you read the attributes. The
XxxAttributeView
lets you read as well as update the attributes. If you only want to
read the attributes, use
XxxAttributes
. If you want to read and update attributes, use
XxxAttributeView
as well as
XxxAttributes
.
The following two methods of the
Files
class let you read the file attributes in a bulk, which is much more
efficient than reading one attribute at a time.
•
<A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type,
LinkOption... options)
Map<String,Object> readAttributes(Path path, String attributes, LinkOption...
options)
The last argument of both methods lets you specify how a symbolic link is handled. By default, if a file is a
symbolic link, the attributes of the target of the symbolic link are read. If you specify
NOFOLLOW_LINKS
as the option,
the attributes of the symbolic link are read, not the attributes of its target.
The first
readAttributes()
method returns all file attributes of a specified type in an
XxxAttributes
object.
For example, you would write the following snippet of code to read the basic file attributes:
•
// Create the Path object representing the path of the file
Path path = Paths.get("C:\\poems\\luci1.txt");
// Read the basic file attributes
BasicFileAttributes bfa =
Files.readAttributes(path, BasicFileAttributes.class);
// Get the last modified time
FileTime lastModifiedTime = bfa.lastModifiedTime();
// Get the size of the file
long size = bfa.size();
The second
readAttributes()
method returns all or some of the attributes of a specific type. The list of attributes
to read is supplied in a string form. The string form of an attribute list uses the following syntax:
view-name:comma-separated-attributes
The
view-name
is the name of the attribute view that you want to read, such as
basic
,
posix
,
acl
, etc.
If
view-name
is omitted, it defaults to
basic
. If
view-name
is present, it is followed by a colon. You can read all
attributes of a specific view type by specifying an asterisk as the attributes list. For example, you can specify
"basic:*"
or
"*"
to read all basic file attributes. To read the size and the last modified time of the basic view, you would use
"basic:size,lastModifiedTime"
or
"size,lastModifiedTime"
. To read the owner attribute of a file using an
ACL view, you would use a string
"acl:owner"
. To read all
posix
attributes of a file, you would use
"posix:*"
.
The following snippet of code prints the size and the last modified time of the file
C:\poems\luci1.txt
. Note that
the file path uses Windows syntax.
// Get a Path object
Path path = Paths.get("C:\\poems\\luci1.txt");
// Prepare the attribute list
String attribList = "basic:size,lastModifiedTime";