Get file owner metadata information with java

2019-05-16 10:54发布

问题:

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?

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

}


回答2:

Use BasicFileAttributes instead.

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

Posix file attributes are not supported in Windows.



回答3:

Here is is a sample for files permissions on UNIX/Linux platforms

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

class A { 
    public static void main(String[] args) throws Exception
    { 
        //Make sure file exists e.g. Unix path structure
       Path p = Paths.get("/a/b/Log.txt");
       PosixFileAttributes posix = Files.readAttributes(p,        
       PosixFileAttributes.class);

       //Set Permissions if needs be for the file Log.txt
       Set<PosixFilePermission> perms =   
           PosixFilePermissions.fromString("rw-r--r--");
       Files.setPosixFilePermissions(p, perms);

       //Output the various attributes of the file named Log.txt
       System.out.println(posix.group());
       System.out.println(posix.permissions());
       System.out.println(posix.owner());

    }
 }