Read File attribute
import java.io.IOException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFileAttributes; public class ReadAttributesExample { public static void main(String[] args) throws IOException { // You need to make sure the next file exists... Path pUnix = Paths.get("/home/macluq/tmp/file1.txt"); // use this if you are on Windows // Path pWin = Paths.get("C:\\tmp\\file1.txt"); PosixFileAttributes fa = Files.readAttributes(pUnix, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); // DosFileAttributes dfa = Files.readAttributes(pWin, DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS); // Change from fa to dfa if you're in Windows System.out.println("Creation time " + fa.creationTime()); System.out.println("File key " + fa.fileKey()); System.out.println("Is directory? " + fa.isDirectory()); System.out.println("Is other? " + fa.isOther()); System.out.println("Is regular file? " + fa.isRegularFile()); System.out.println("Is symbolic link? " + fa.isSymbolicLink()); System.out.println("Last access time " + fa.lastAccessTime()); System.out.println("Last modified time " + fa.lastModifiedTime()); System.out.println("Size " + fa.size()); // Unix specific, comment out if you're in Windows System.out.println("Group " + fa.group().getName()); System.out.println("Owner " + fa.owner().getName()); System.out.println("Permissions " + fa.permissions().toString()); // Dos specific, uncomment if you're in Windows // System.out.println("Is archive? " + dfa.isArchive()); // System.out.println("Is hidden? " + dfa.isHidden()); // System.out.println("Is read only? " + dfa.isReadOnly()); // System.out.println("Is system? " + dfa.isSystem()); }/*from w w w . j av a 2 s .c o m*/ }
Be careful with the following code
Path pUnix = Paths.get("/tmp/file1.txt"); BasicFileAttributes bfaNotToBeUsed = Files.readAttributes(pUnix, DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
If you uncomment the previous line, you'll see how it compiles, but it throws an exception unless you're on Windows.
But it compiles even if the interface is not the same... because DFA is subinterface of BFA!
Path pUnix = Paths.get("/tmp/file1.txt"); DosFileAttributes dfa = Files.readAttributes(pUnix, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
this does NOT compile, the interface is not the same and we are assigning the superinterface...