如何在Java中获取文件所有者名称?
根据问题陈述,我们将找到Java中的文件所有者名称。这里的拥有者名称表示运行文件的PC的所有者。要在Java中查找文件所有者,我们将使用FileOwnerAttributeView类的getOwner()方法。
FileOwnerAttributeView属于java.nio类。
让我们深入研究本文,了解如何使用Java编程语言来实现它。
向您展示一些实例
实例-1
假设给定的文件位置是“D:/saket.txt”。
检查给定文件的所有者名称后,输出将为:
文件的所有者是:LAPTOP-9IH5RA2V\SAKET
实例-2
假设给定的文件位置是“C:/Users/SAKET/Desktop/saket/Work”。
检查给定文件的所有者名称后,输出将为:
文件的所有者是:LAPTOP-9IH5RA2V\SAKET
算法
步骤1 - 以文件路径作为输入。
步骤2 - 使用FileOwnerAttributeView类创建一个具有文件属性的对象。
步骤3 - 声明try和catch块以避免任何错误。
步骤4 - 使用getOwner()方法从文件中提取所有者名称。
步骤5 - 打印结果。
语法
getOwner() - 用于返回或获取给定文件的当前所有者。它属于Java中的FileOwnerAttributeView类。
以下是它的语法
file_attribute_object.getOwner()
多种方法
我们提供了不同方法的解决方案。
使用静态输入。
使用用户定义的方法
让我们一一查看程序及其输出。
注意 - 在任何在线编辑器上执行这些程序可能无法提供正确的输出。因为在线Java编辑器无法访问您的本地系统的文件。因此,要获得预期的输出,建议您在系统中存在的本地Java编辑器中运行这些程序。
方法-1:使用静态输入
在这种方法中,文件路径将作为静态输入获取。然后根据算法获取文件所有者的名称。
示例
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
public class Main {
//main method
public static void main(String[] args) {
// Taking file path as input
Path path = Paths.get("D:/saket.txt");
// Create object having the file attribute
FileOwnerAttributeView file = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
// Declaring try and catch block to avoid any errors
try {
// Extracting owner name from the file
UserPrincipal user = file.getOwner();
// Printing the owner's name as a result
System.out.println("The Owner of the file is: " + user.getName());
}
//catch block
catch (Exception e){
System.out.println(e);
}
}
}
输出
java.nio.file.NoSuchFileException: D:/saket.txt
方法-2:使用用户定义的方法
在这种方法中,文件路径将作为输入获取。然后通过将此文件路径作为参数调用用户定义的方法,并根据算法获取文件所有者的名称。
示例
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
public class Main{
//main method
public static void main(String[] args) {
// calling user defined method
func();
}
//user defined method
static void func() {
// Taking file path as input
Path path = Paths.get("C:/Users/SAKET KASHYAP/Desktop/saket/Work");
// Create object having the file attribute
FileOwnerAttributeView file = Files.getFileAttributeView(path,FileOwnerAttributeView.class);
// Declaring try and catch block to avoid any errors
try {
// Extracting owner name from the file
UserPrincipal user = file.getOwner();
// Printing the owner's name as a result
System.out.println("The Owner of the file is: " + user.getName());
}
//catch block
catch (Exception e){
System.out.println(e);
}
}
}
输出
java.nio.file.NoSuchFileException: C:/Users/SAKET KASHYAP/Desktop/saket/Work
在这篇文章中,我们探讨了使用Java编程语言检查文件所有者名称的不同方法。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP