【问题标题】:Check if file or folder is open before delete [duplicate]在删除之前检查文件或文件夹是否打开[重复]
【发布时间】: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();
    }
    

【问题讨论】:

标签: java


【解决方案1】:

你可以使用Apache commons io api,

  boolean flagFileNotInUse = false;
try {
    org.apache.commons.io.FileUtils.touch(yourFile);
    flagFileNotInUse = true;
} catch (IOException e) {
    flagFileNotInUse = false;
}

// 然后检查 flagFileNotInUse 的值,

  flagFileNotInUse = true, means file not in use
  flagFileNotInUse = false, means file in use

【讨论】:

  • 如果您将 bool flagFileNotInUse 命名或交换 flag 的值,不是更清楚吗?
  • @RFerwerda :请参阅更新后的帖子。
  • 以上代码适用于文件夹但不适用于文件@DarkKnight
猜你喜欢
  • 1970-01-01
  • 2015-04-19
  • 2023-04-10
  • 1970-01-01
  • 2019-03-30
  • 1970-01-01
  • 1970-01-01
  • 2016-02-10
  • 2018-02-20
相关资源
最近更新 更多