我尝试了很多例子,但没有人工作.
我尝试这个但是不行.
我尝试这个但是不行.
我也尝试使用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类抛出:
@H_502_19@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