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

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

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

我知道,基于Unix的系统允许在多个进程中打开文件…有没有类似的技巧,以取得相同的结果为基于Unix系统?

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

Solutions Collecting From Web of "如何检查一个文件是否被另一个进程打开(Java / Linux)?"

下面是一个如何在基于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; } 

希望这可以帮助。

您可以从Java程序运行lsof Unix实用程序,告诉您哪个进程正在使用文件,然后分析其输出。 要从Java代码运行程序,请使用RuntimeProcessProcessBuilder类。 注意:在这种情况下,Java程序将不能移植,这与可移植性概念相矛盾,所以请三思而后行,是否真的需要这个:)

这个也应该适用于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; } 

感谢您的原始建议。 我有一个小小的升级,对这个方法有点重要:

 FileOutputStream fos = null; try { // Make sure that the output stream is in Append mode. Otherwise you will // truncate your file, which probably isn't what you want to do :-) fos = new FileOutputStream(file, true); // -> file was closed } catch(IOException e) { // -> file still open } finally { if(fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } 

干杯,Gumbatron

您可以尝试这个信号量类型代码的@ZZ编码器的文件锁定

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