假设我将一个包含目录路径的字符串传递给一个随机方法。在此方法开始工作之前,它应该检查目录或其任何内容是否被锁定。我认为这将是一项简单的任务,但结果我得到了一些几乎不简单的代码来完成它。你有什么建议如何改进它或至少让它更短吗?
如果您认为这已经是最好的解决方案,请投赞成票并继续解决实际问题:P
public static boolean checkLocks(String path) {
File f = new File(path);
if(f.isDirectory()) {
boolean ans = true;;
String files[] = f.list();
for (String file : files) {
File ff = new File(f, file);
ans = checkLocks(ff.toString());
if(!ans){
break;
}
}
return ans;
} else {
try {
RandomAccessFile stream = new RandomAccessFile(path, "rw");
FileChannel channel = stream.getChannel();
FileLock lock = null;
try {
lock = channel.tryLock();
} catch (final OverlappingFileLockException e) {
stream.close();
channel.close();
System.out.println("File at "+path+" locked");
return false;
}
stream.close();
channel.close();
return true;
} catch (IOException eio) {
System.out.println("File at "+path+" does not exits");
return false;
}
}
}
慕姐8265434
慕的地10843
MMTTMM
相关分类