How to Get Owner of a File in Java

In this example, I show you how to get the owner of the file in Java using Files.getOwner() API.

java.nio.file.Files.getOwner() API

This method returns the owner of a file.
The path parameter is associated with a file system that supports FileOwnerAttributeView
This file attribute view provides access to a file attribute that is the owner of the file.

Java Files.getOwner API Example

In the example, we get the owner of the file in Java.
package net.javaguides.corejava.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserPrincipal;

public class JavaGetFileOwner {

    public static void main(String[] args) throws IOException {

        Path myPath = Paths.get("src/sample.txt");

        UserPrincipal userPrincipal = Files.getOwner(myPath);
        String owner = userPrincipal.getName();

        System.out.println(owner);
    }
}
Output:
Ramesh\CM-1787

Reference


Comments