【发布时间】:2013-11-05 07:37:16
【问题描述】:
- 如何在我尝试删除文件/文件夹之前检查它是否打开。
正在以编程方式删除它..在删除之前,需要检查它是否打开
-
我想要这样的东西,
if(file/folder is open){ //do not delete it }else{ //delete it }我尝试了以下两个代码集,但没有任何效果
File scrptFile=new File(dirFile); boolean isFileUnlocked = false; try { org.apache.commons.io.FileUtils.touch(scrptFile); isFileUnlocked = true; } catch (IOException e) { isFileUnlocked = false; } if(isFileUnlocked){ // Do stuff you need to do with a file that is NOT locked. System.out.println("file is not locked"); } else { // Do stuff you need to do with a file that IS locked System.out.println("file is locked"); } File file = new File(dirFile); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); // Get an exclusive lock on the whole file FileLock lock = channel.lock(); try { lock = channel.tryLock(); // Ok. You get the lock System.out.println("Ok. You get the lock"); } catch (OverlappingFileLockException e) { // File is open by someone else System.out.println("File is open by someone else"); } finally { lock.release(); }
【问题讨论】:
-
有趣的想法,但考虑到文件锁依赖于操作系统(并且在某些具有多种不同方法的操作系统下),可能很难以干净的方式确定。最好的方法是尝试。 File#delete 如果由于某种原因无法删除文件,则返回 false
标签: java