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