加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何确定另一个进程是否正在使用该文件(Java)

发布时间:2020-12-14 19:35:32 所属栏目:Java 来源:网络整理
导读:我尝试了很多例子,但没有人工作. 我尝试这个但是不行. 我也尝试使用tryLock().它总是返回false.为什么? private boolean checkCompleteFile(File f){ RandomAccessFile file = null; FileLock fileLock = null; try { file = new RandomAccessFile(f,"rw");
我尝试了很多例子,但没有人工作.
我尝试这个但是不行.

我也尝试使用tryLock().它总是返回false.为什么?

private boolean checkCompleteFile(File f)
{           
    RandomAccessFile file = null;
    FileLock fileLock = null;

    try
    {
        file = new RandomAccessFile(f,"rw");
        FileChannel fileChannel = file.getChannel();

        fileLock = fileChannel.lock();
        if (fileLock != null)
        {
            fileLock.release();
            file.close();
            return false;
        }

    }
    catch(Exception e)
    {
         return false;
    }

    return true;
}

解决方法

你捕获一个异常并返回false,这就是为什么你一直都是假的,对异常做一些事情或者没有抓住它所以你知道是否抛出异常,如果你捕到一般异常,那么错误的返回值实际上没有意义.
try {
  lock = channel.tryLock();
  // ...
} catch (OverlappingFileLockException e) {
  // File is already locked in this thread or virtual machine
}
lock.release();
channel.close();

您可以尝试访问该文件并在失败时捕获异常:

boolean isLocked=false;
RandomAccessFile fos=null;
try {
      File file = new File(filename);
      if(file.exists())
        fos=new RandomAccessFile(file,"rw");        
}catch (FileNotFoundException e) {
    isLocked = true;
}catch (SecurityException e) {
    isLocked = true;
}catch (Exception e) {
    // handle exception
}finally {
    try {
        if(fos!=null) {
            fos.close();
        }
    }catch(Exception e) {
        //handle exception
    }
}

请注意,RandomAccessFile类抛出:

FileNotFoundException

if the mode is “r” but the given string does
not denote an existing regular file,or if the mode begins with “rw”
but the given string does not denote an existing,writable regular
file and a new regular file of that name cannot be created
,or if some
other error occurs while opening or creating the file.

SecurityException

if a security manager exists and its checkRead method denies read access to the file or the mode is “rw” and the security manager’s checkWrite method denies write access to the file

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读