Get file owner metadata information with java

10,137

Solution 1

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());
    }

}

Solution 2

Use BasicFileAttributes instead.

BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);

Posix file attributes are not supported in Windows.

Share:
10,137
Mario
Author by

Mario

Updated on July 11, 2022

Comments

  • Mario
    Mario almost 2 years

    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?