Lấy danh sách các ổ đĩa trong hệ thống
File[] drives = File.listRoots();
if (drives != null && drives.length > 0) {
for (File aDrive : drives) {
System.out.println(aDrive);
}
}
Nếu hệ điều hành là Windows thì sẻ hiện lên các ổ đĩa như C:\, D:\…
Nếu là Linux, Unix thì sẻ hiện lên \(root)
Lấy thông tin mô tả của từng ổ đĩa
FileSystemView fsv = FileSystemView.getFileSystemView(); String driveType = fsv.getSystemTypeDescription(aDrive);
Lấy tổng không gian đĩa và khỏang không gian trống của từng ổ đĩa
Windows
File aDrive = new File("C:");
long freeSpace = aDrive.getFreeSpace();
long totalSpace = aDrive.getTotalSpace();
Linux
File aDrive = new File("\\"); long freeSpace = aDrive.getFreeSpace();
long totalSpace = aDrive.getTotalSpace();
Code ví dụ tổng hợp các phần khi nảy
public class DrivesListingExample {
public static void main(String[] args) {
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] drives = File.listRoots();
if (drives != null && drives.length > 0) {
for (File aDrive : drives) {
System.out.println("Drive Letter: " + aDrive);
System.out.println("\tType: " + fsv.getSystemTypeDescription(aDrive));
System.out.println("\tTotal space: " + aDrive.getTotalSpace());
System.out.println("\tFree space: " + aDrive.getFreeSpace());
System.out.println();
}
}
}
}