Paul J Abernathy
Paul J Abernathy

Reputation: 1003

getting file creator/owner attributes in Java

I am trying to read in a list of files and find the user who created the file. With a *nix system, you can do something like

Map<String, Object> attrs = Files.readAttributes(Paths.get(filename), "posix:*");

However, when attempting it on a Windows system, I get an error because Windows is not able to access the POSIX properties. You can get the "regular" (non POSIX) properties by doing this:

attrs = Files.readAttributes(Paths.get(filename), "*");

But the file's creator is not included in that list.

Is there any way to find out who created the file in a Java program running on Windows?

Upvotes: 7

Views: 2149

Answers (2)

BDRSuite
BDRSuite

Reputation: 1612

You can use the FileOwnerAttributeView to get the Owner info:

Path filePath = Paths.get("your_file_path_goes_here");
FileOwnerAttributeView ownerInfo = Files.getFileAttributeView(filePath,  FileOwnerAttributeView.class);
UserPrincipal fileOwner = ownerInfo.getOwner();
System.out.println("File Owned by: " + fileOwner.getName());

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

I believe you can use Files.getOwner(Path, LinkOption...) to get the current owner (which may also be the creator) like

Path path = Paths.get("c:\\path\\to\\file.ext");
try {
    UserPrincipal owner = Files.getOwner(path, LinkOption.NOFOLLOW_LINKS);
    String username = owner.getName();
} catch (IOException e) {
    e.printStackTrace();
}

This should work if it is a file system that supports FileOwnerAttributeView. This file attribute view provides access to a file attribute that is the owner of the file.

Upvotes: 4

Related Questions