我想检查某个java.io.File是否被外部程序打开。 在Windows上,我使用这个简单的技巧:
try { FileOutputStream fos = new FileOutputStream(file); // -> file was closed } catch(IOException e) { // -> file still open }
我知道,基于Unix的系统允许在多个进程中打开文件…有没有类似的技巧,以取得相同的结果为基于Unix系统?
任何帮助/黑客高度赞赏:-)
在C中对文件进行sorting
Linux上文件的CPU使用情况
如何使用linux命令从纯文本文件中删除重复的单词
合并文件(猫)在每个文件夹的Unix
如何使用lseek检查文件中的当前偏移位置?
查找当前目录中的所有可写文件
如何findWindows可执行文件在运行时打开或访问的所有文件?
如何将特殊字符(如尖括号)输出到HTML / XHTML / XML文件中?
文件扩展名
替代epoll_wait,它不等待文件描述符?
下面是一个如何在基于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代码运行程序,请使用Runtime , Process , ProcessBuilder类。 注意:在这种情况下,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(); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。