Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file owner metadata information with java

I am trying to retrieve the owner of a file, using this code:

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

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

taken from oracle's page (http://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html)

but i always get a UnsupportedOperationException at the line i indicate above.

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

I think that 'readAttributes' method is abstract and this cause the exception, but (if this is true) i don't know how to implement this method in order to give me the file attributes.

Does anyone know how to implement this method, or an alternative method (that is tested) to get the file owner?

like image 648
Mario Avatar asked Dec 08 '22 08:12

Mario


1 Answers

Try this - works also on 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());
    }

}
like image 146
drkunibar Avatar answered Dec 10 '22 21:12

drkunibar