我正在尝试检查某个java.io.File是否被外部程序打开。在windows上,我使用这个简单的技巧:
try {
FileOutputStream fos = new FileOutputStream(file);
// -> file was closed
} catch(IOException e) {
// -> file still open
}我知道基于unix的系统允许在多个进程中打开文件...对于基于unix的系统,有没有类似的技巧可以达到同样的结果?
非常感谢任何帮助/黑客:-)
发布于 2013-05-22 15:35:38
下面是一个如何在基于的系统中使用unix lsof的示例:
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;
}希望这能有所帮助。
发布于 2012-02-18 21:46:35
您可以从Java程序运行lsof Unix实用程序,它会告诉您哪个进程正在使用某个文件,然后分析其输出。要从Java代码运行程序,可以使用例如Runtime、Process、ProcessBuilder类。注意:在这种情况下,您的Java程序将不是可移植的,这与可移植性概念相矛盾,因此请三思而后行,您是否真的需要这样:)
发布于 2013-07-08 21:09:01
这一点也应该适用于Windows系统。但是注意,Linux是不起作用的!
private boolean isFileClosed(File file) {
boolean closed;
Channel channel = null;
try {
channel = new RandomAccessFile(file, "rw").getChannel();
closed = true;
} catch(Exception ex) {
closed = false;
} finally {
if(channel!=null) {
try {
channel.close();
} catch (IOException ex) {
// exception handling
}
}
}
return closed;
}https://stackoverflow.com/questions/9341505
复制相似问题