Java 如何获取文件所有者的名称

Java 如何获取文件所有者的名称

根据问题描述,我们将在Java中找到文件所有者的名称。这里的所有者名称表示运行文件的计算机的所有者。要在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编程语言探索了不同的方法来检查文件所有者的名称。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程