如何在 Java 中獲取檔案儲存型別?


在 Java 中,java.nio.file.FileStore 類表示儲存池、裝置、分割槽、卷或其他實現特定的檔案儲存方式。FileStore 類提供方法來查詢有關儲存裝置的資訊,例如其總空間和可用空間、檔案系統型別,以及它是否支援某些功能,如檔案屬性或符號連結。

FileStore 類的 type() 方法返回一個表示檔案儲存型別的字串。檔案儲存型別是一個字串,用於標識檔案儲存使用的檔案系統型別。檔案系統型別的示例包括 Windows NT 檔案系統的“NTFS”、Linux 使用的第四擴充套件檔案系統的“ext4”以及 macOS 使用的分層檔案系統的“HFS+”。

讓我們開始吧!

例如

假設原始檔為

" C:/Users/SAMPLE /Desktop/Tutorial/Program/example.txt”

執行獲取儲存型別操作後,結果將是

檔案儲存型別:NTFS

演算法

步驟 1:宣告並初始化原始檔路徑。

步驟 2:建立 FileStore 物件。

步驟 3:使用 type() 方法獲取檔案的檔案儲存型別。

步驟 4:列印結果。

語法

getFileStore():它是在 java.nio.file.Path 類中定義的方法。它用於獲取表示檔案儲存或檔案所在分割槽的 FileStore 物件。

多種方法

我們提供了不同方法的解決方案。

  • 使用靜態方法

  • 使用使用者自定義方法

讓我們逐一檢視程式及其輸出。

方法 1:使用靜態方法

在此方法中,我們將分配預設檔案系統。然後,根據演算法,我們將檢查 Java 中是否打開了特定檔案系統。

在此方法中,將分配路徑位置。然後,根據演算法,我們將瞭解 Java 中的檔案儲存型別。

示例

import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main
{
   //main method
   public static void main(String[] args)
   {
      //getting the file path
      Path path = 
Paths.get("C:/Users/SAMPLE/Desktop/Tutorial/Program/example.txt");
      //try block
      try {
         //getting the FileStore object
         FileStore store = Files.getFileStore(path);
         //getting the file store type 
         String type = store.type();
         
         //print the result
         System.out.println("File store type: " + type);  
      //catch block
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

輸出

File store type: NTFS

方法 2:使用使用者自定義方法

在此方法中,將分配檔案路徑。然後,透過傳遞給定值來呼叫使用者自定義方法,並根據演算法,我們將瞭解 Java 中的檔案儲存型別。

示例

import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main2
{
   //main method
   public static void main(String[] args)
   {
      //calling user defined method
      checkFileStoreType();
   }
   //user defined method
   static void checkFileStoreType()
   {
      
      //getting the file path
      Path path = Paths.get("C:/Users/SAMPLE/Desktop/Learn/Program/myfile.txt");
      //try block
      try {  
         //getting the FileStore object
         FileStore store = Files.getFileStore(path);
         
         //getting the file store type 
         String type = store.type();
         
         //print the result
         System.out.println("File store type: " + type);
         
      //catch block
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

輸出

File store type: NTFS

在本文中,我們探討了如何使用 Java 程式語言來了解檔案儲存型別。

更新於: 2023 年 8 月 17 日

140 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.