如何检查文件是否被其他进程(Java / Linux)打开? [英] How to check if a file is open by another process (Java/Linux)?

查看:697
本文介绍了如何检查文件是否被其他进程(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;
}

希望这有帮助。

这篇关于如何检查文件是否被其他进程(Java / Linux)打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆