使用java获取文件所有者元数据信息 [英] 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());
取自oracle的页面( http://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html )
taken from oracle's page (http://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html)
但我总是在上面指示的行上得到UnsupportedOperationException。
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)
我认为'readAttributes'方法是抽象的,这会导致异常,但是(如果这是真的)我不知道如何实现此方法以便为我提供文件属性。
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?
推荐答案
试试这个 - 也适用于Windows
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());
}
}
这篇关于使用java获取文件所有者元数据信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!