How to check if a file is open by another process (Java/Linux)?

前端 未结 5 718
抹茶落季
抹茶落季 2020-12-08 14:30

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 FileO         


        
5条回答
  •  隐瞒了意图╮
    2020-12-08 14:52

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

    Hope this helps.

提交回复
热议问题