Get metadata information of file owner using java

I am trying to retrieve the owner of the file using the following code:

Path file = Paths.get( fileToExtract.getAbsolutePath() );
    PosixFileAttributes attr = Files.readAttributes(file,PosixFileAttributes.class); //line that throws exception

    System.out.println(attr.owner.getName());

Excerpt from Oracle page( http://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html )

But I always get unsupported operationexception on the line indicated above

java.lang.UnsupportedOperationException
at sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:192)
at java.nio.file.Files.readAttributes(Files.java:1684)

I think the 'readattributes' method is abstract, which will cause exceptions, but (if this is true) I don't know how to implement this method to give me file attributes

Who knows how to implement this method, or another method (tested) to get the file owner?

Solution

Try this – also for windows

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.UserPrincipal;

public class FileOwner {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("/tmp");
        FileOwnerAttributeView ownerAttributeView = Files.getFileAttributeView(path,FileOwnerAttributeView.class);
        UserPrincipal owner = ownerAttributeView.getOwner();
        System.out.println("owner: " + owner.getName());
    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>