Reputation: 139
I'm working on a Java app and I need to check if a removable drive is in use before ejecting it programatically.
Is it possible to check a drive for open/in-use files in pure Java? As a fallback, is there a shell command that I could call from Java which would do this kind of checking? Ideally, I'd need commands for both Windows and MacOS.
Upvotes: 0
Views: 91
Reputation: 166
In Java, directly checking if a drive is in use (i.e., if files on the drive are open) is not straightforward due to platform-independent restrictions and security concerns. However, you can use platform-specific methods to achieve this indirectly.
For Windows, you can execute the 'handle'
command-line tool using Java's ProcessBuilder
to check for open handles on a specific drive. Here's an example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
String driveLetter = "E:"; // Replace with the drive letter you want to check
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "handle", driveLetter);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
// Check for any open handles on the drive
if (line.contains(driveLetter)) {
System.out.println("Drive is in use.");
break;
}
}
// Close the reader and wait for the process to finish
reader.close();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
For maxOS, you can use the 'lsof'
command to list open files. Something like this may work depending on your usecase:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
String mountPoint = "/Volumes/MyDrive"; // Replace with the mount point of the drive you want to check
ProcessBuilder processBuilder = new ProcessBuilder("lsof", mountPoint);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
boolean inUse = false;
while ((line = reader.readLine()) != null) {
// Check if there are any open files on the drive
if (line.contains(mountPoint)) {
inUse = true;
break;
}
}
if (inUse) {
System.out.println("Drive is in use.");
} else {
System.out.println("Drive is not in use.");
}
// Close the reader and wait for the process to finish
reader.close();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Upvotes: 1