Write a java program to Get the files owner name


This Java code defines a class Owner_File with a main method that prompts the user to enter the path of a file and prints the owner of the file.

The program uses the Scanner class to read a string from the standard input, which is assumed to be the path of the file. The Paths.get method is then used to create a Path object from the string.

The Files.getFileAttributeView method is called with the file_path and FileOwnerAttributeView.class parameters to obtain an object of the FileOwnerAttributeView class, which represents the owner attribute of the file.

The getOwner method of the FileOwnerAttributeView object is called to get the UserPrincipal object that represents the owner of the file. The getName method of the UserPrincipal object is then called to get the name of the owner, which is printed to the standard output using System.out.println.

Note that this code assumes that the user enters a valid path to an existing file. If the path is invalid or the file does not exist, the program will throw an exception.

Source Code

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Scanner;
public class Owner_File
{
	public static void main(String[] args) throws Exception
	{
		Scanner in = new Scanner(System.in);
		System.out.print("Enter the File Path : ");
		String a = in.next();
		Path file_path = Paths.get(a);
 
		// create object of file attribute.
		FileOwnerAttributeView view = Files.getFileAttributeView(file_path,
		FileOwnerAttributeView.class);
 
		//get the owner information.
		UserPrincipal res = view.getOwner();		
		System.out.println("Owner of the File is : " + res.getName());
	}
}

Output