在 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