如何在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程式語言檢查檔案所有者名稱的不同方法。

更新於: 2023年3月9日

883 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告