如何检查文件是否被另一个进程(Java/Linux)打开?

sal*_*inx 26 java linux file

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

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

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

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

Han*_*ein 10

以下是如何将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;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


sal*_*inx 5

这个也应该适用于 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;
    }
Run Code Online (Sandbox Code Playgroud)


Ais*_*iva 0

您可以尝试@ZZ Coder 的文件锁信号量类型代码

File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

FileLock lock = channel.lock();
try {
    lock = channel.tryLock();
    // Ok. You get the lock
} catch (OverlappingFileLockException e) {
    // File is open by someone else
  } finally {
   lock.release();
}
Run Code Online (Sandbox Code Playgroud)

  • 仅当其他人都使用此代码时才有效。一点也不现实。 (3认同)
  • 它不适用于 ubuntu/linux。即使文件已在另一个进程中打开,文件系统也允许我获取锁。但它适用于 Windows。有人知道如何在 Linux 上实现相同的结果吗??? (3认同)