在 Java 中获取系统的基本根目录
基本根目录、根文件夹或根是指系统的基本或主驱动器。它们具有最高的层次结构,并且是特定文件夹结构的起点或开始。根目录包含其中的所有其他文件夹和文件。
根据问题陈述,我们必须获取系统的基本目录。目录的数量取决于系统,因为它因系统而异。可以通过对单个驱动器/目录进行分区来创建多个驱动器/目录。
让我们探索本文,了解如何使用 Java 编程语言来实现。
为您展示一些实例
实例 1
假设我们的系统中有 5 个目录。
那么程序应该列出这些驱动器。
Ex- Drive C Drive D Drive E Drive F Drive G
实例 2
假设我们的系统中只有一个目录。
那么程序应该列出这些驱动器。
Ex- Drive C
算法
步骤 1 - 导入 java.io.File 包
步骤 2 - 创建一个 File 对象数组,并使用 listRoots() 函数存储根目录。
步骤 3 - 使用 for 循环迭代数组的所有元素并打印它们。
语法
要获取根目录,我们需要调用名为 listRoots() 的 File 类函数。
以下是该方法的语法:
File[] object_name = File.listRoots()
要获取诸如根分区、文件类型信息或隐藏文件位等详细信息,这些信息通常无法通过 File API 访问。要使用其方法,我们需要创建一个类对象。
以下是创建此类对象的语法:
FileSystemView fsv = FileSystemView.getFileSystemView();
多种方法
我们提供了不同方法的解决方案
打印所有根目录
打印所有带有详细信息的根目录。
让我们逐一查看程序及其输出。
方法 1:打印所有根目录
在这种方法中,我们使用 File 类的 listRoots() 方法并将其打印出来,以获取系统中的基本根目录。
示例
import java.io.File;
public class Main {
public static void main(String args[]) {
// Created an array of file objects to store the root directories
File[] rootDrive = File.listRoots();
// Use a for loop to print out the array elements
for (File sysDrive : rootDrive) {
System.out.println("Drive : " + sysDrive);
}
}
}
输出
Drive : /
方法 2:打印所有带有详细信息的根目录
在这种方法中,我们像前面方法一样使用 File 类的 listRoots() 方法,并结合使用 FileSystemView 类来打印目录及其类型、可用空间和总空间。
示例
import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class Main {
// Constant that stores 1 gigabyte in bytes
static long gbConvert = 1073741824l;
public static void main(String args[]) {
// Created a filesystemview object to store
FileSystemView fsv = FileSystemView.getFileSystemView();
// Created an array of file objects to store the root directories
File[] rootDrive = File.listRoots();
// Use a for loop to print out the array elements
for (File sysDrive : rootDrive) {
// Print drive letter
System.out.println("Drive : " + sysDrive);
// Print the disk type
System.out.println("Type: " +
fsv.getSystemTypeDescription(sysDrive));
// Print the space occupied and total space
System.out.println("Space occupied(in GB): " + (sysDrive.getTotalSpace() - sysDrive.getFreeSpace()) / gbConvert + "/"
+ sysDrive.getTotalSpace() / gbConvert);
System.out.println();
}
}
}
输出
Drive : / Type: null Space occupied(in GB): 122/874
在本文中,我们探索了使用 Java 编程语言获取基本目录及其详细信息的不同方法。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP