如何检查文件是否被其他进程(Java / Linux)打开?

如何检查文件是否被其他进程(Java / Linux)打开?

问题描述:

我正在尝试检查某个java.io.File是否由外部程序打开。在Windows上我使用这个简单的技巧:

I am trying to check if a certain java.io.File is open by an external program. On windows I use this simple trick:

try {
    FileOutputStream fos = new FileOutputStream(file);
    // -> file was closed
} catch(IOException e) {
    // -> file still open
}

我知道基于unix的系统允许在多个进程中打开文件...对于基于unix的系统,是否有类似的技巧来实现相同的结果?

I know that unix based systems allow to open files in multiple processes... Is there a similar trick to achieve the same result for unix based systems ?

任何帮助/ hack高度赞赏: - )

Any help / hack highly appreciated :-)

以下是基于unix的系统如何使用 lsof 的示例:

Here's a sample how to use lsof for unix based systems:

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;
}

希望这有帮助。