Java Reference
In-Depth Information
8-10.
Querying
(and
Setting)
File
Metadata
Problem
You need to get information about a particular file, such as file size, whether it is a dir-
ectory, and so on. Also, you might want to mark a file as archived in the Windows op-
erating system or grant specific POSIX file permissions in the *nix operating system
(refer to Recipe 8-8).
Solution
Using Java NIO.2 you can obtain any file information by simply invoking methods on
the java.nio.file.Files utility class, passing the path for which you'd like to
obtain the metadata. You can obtain attribute information by calling the
Files.getFileAttributeView() method, passing the specific implementation
for the attribute view that you would like to use. The following code demonstrates
these techniques for obtaining metadata.
Path path = FileSystems.getDefault().getPath("./
file2.log");
try {
// General file attributes, supported by all Java
systems
System.out.println("File Size:"+Files.size(path));
System.out.println("Is
Directory:"+Files.isDirectory(path));
System.out.println("Is Regular
File:"+Files.isRegularFile(path));
System.out.println("Is Symbolic
Link:"+Files.isSymbolicLink(path));
System.out.println("Is Hidden:"+Files.isHidden(path));
System.out.println("Last Modified
Time:"+Files.getLastModifiedTime(path));
System.out.println("Owner:"+Files.getOwner(path));
Search WWH ::




Custom Search