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

你捕获一个异常并返回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

}

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值