Java 如何知道文件存储类型

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类中定义的方法。它用于获取表示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编程语言来了解文件存储类型。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程