Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determinate if 2 logical drives are on the same physical disc in Java

Imagine a PC with an SSD, and a HDD.

SSD is splitted to 2 partitions: C and D.

HDD is splitted to 2 partitions: E and F.

I need to create a method:

boolean isOnSamePhysicalDrive(String drive1, String drive2);

isOnSamePhysicalDrive("C", "D") --> true

isOnSamePhysicalDrive("E", "F") --> true

isOnSamePhysicalDrive("C", "E") --> false

like image 518
Saphyra Avatar asked Mar 18 '19 20:03

Saphyra


1 Answers

Java.nio.file.FileStore is what you are looking for.

https://docs.oracle.com/javase/7/docs/api/java/nio/file/FileStore.html

Storage for files. A FileStore represents a storage pool, device, partition, volume, concrete file system or other implementation specific means of file storage.

This code prints the names of my partitions when executed.

for (FileStore fs: FileSystems.getDefault().getFileStores()) {
    System.out.println("Name: " + fs.name());
    System.out.println("Type: " + fs.type());
}

As such

Name: SSD
Type: NTFS
Name: Door systeem gereserveerd
Type: NTFS
Name: 
Type: NTFS

Note that Door systeem gereserveerd is a partition of my main drive, SSD. Excuse the Dutch language.

enter image description here

Lokale schijf means Local drive . The disk is unnamed, which is why no name shows up in the results.

To be more specific, you can use this.

System.out.println(Files.getFileStore(Paths.get("C:/")).name());
System.out.println(Files.getFileStore(Paths.get("E:/")).name());

Will print the name of a specific drive or partition. In my case:

SSD
Door systeem gereserveerd
like image 111
Kars Avatar answered Sep 29 '22 03:09

Kars