我正在尝试检查某个 java.io.File 是否被外部程序打开。在 Windows 上,我使用这个简单的技巧:
try {
FileOutputStream fos = new FileOutputStream(file);
// -> file was closed
} catch(IOException e) {
// -> file still open
}
我知道基于 unix 的系统允许在多个进程中打开文件...对于基于 unix 的系统是否有类似的技巧来实现相同的结果?
非常感谢任何帮助/破解 :-)
最佳答案
以下是如何将 lsof 用于基于 unix 的系统的示例:
public static boolean isFileClosed(File file) {
try {
Process plsof = new ProcessBuilder(new String[]{"lsof", "|", "grep", file.getAbsolutePath()}).start();
BufferedReader reader = new BufferedReader(new InputStreamReader(plsof.getInputStream()));
String line;
while((line=reader.readLine())!=null) {
if(line.contains(file.getAbsolutePath())) {
reader.close();
plsof.destroy();
return false;
}
}
} catch(Exception ex) {
// TODO: handle exception ...
}
reader.close();
plsof.destroy();
return true;
}
希望这会有所帮助。
关于java - 如何检查文件是否被另一个进程(Java/Linux)打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9341505/