我正在开发一个 Java 应用程序,我需要在以编程方式弹出可移动驱动器之前检查它是否正在使用。
是否可以在纯 Java 中检查驱动器中是否有打开/正在使用的文件?作为后备方案,是否有一个可以从 Java 调用的 shell 命令来执行此类检查?理想情况下,我需要适用于 Windows 和 MacOS 的命令。
在 Java 中,由于平台无关的限制和安全问题,直接检查驱动器是否正在使用(即驱动器上的文件是否打开)并不简单。但是,您可以使用特定于平台的方法来间接实现此目的。
对于 Windows,您可以使用 Java 的
'handle'
执行 ProcessBuilder
命令行工具来检查特定驱动器上打开的句柄。这是一个例子:
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();
}
}
}
对于 maxOS,您可以使用
'lsof'
命令列出打开的文件。根据您的用例,类似的东西可能会起作用:
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();
}
}
}