下面列出了java.nio.channels.FileLock#close() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns if the given {@code file } is used by any process (i.e.
* has the file open for reading or writing).
*
* @param file to check
* @return if the given {@code file } is used by any process
*/
// Todo: Here is a candidate for Windows. Verify that it works
private static FileState stateWindows(@NotNull File file) {
if (!file.exists()) return FileState.NON_EXISTENT;
try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel fileChannel = randomAccessFile.getChannel()) {
final FileLock fileLock = fileChannel.tryLock();
if (fileLock != null) {
fileLock.close();
return FileState.CLOSED;
}
return FileState.OPEN;
} catch (IOException ignored) {
// Do nothing
}
return FileState.UNDETERMINED;
}
public static void safeClose(FileLock closeable) {
if (closeable != null) {
try {
if (Build.VERSION.SDK_INT > 18) {
closeable.close();
} else {
closeable.release();
}
} catch (Throwable e) {
}
}
}
synchronized boolean isFree()
{
if (_lock != null) {
return false;
}
if (! Files.isReadable(_path)) {
return true;
}
try (FileOutputStream fOs = (FileOutputStream) Files.newOutputStream(_path)) {
FileLock lock = fOs.getChannel().tryLock();
if (lock != null) {
lock.close();
return true;
}
else {
return false;
}
} catch (Exception e) {
log.finer(_path + ": isFree " + e);
log.log(Level.FINEST, e.toString(), e);
return true;
}
}
private static boolean isLocked(File file) {
try {
FileLock lock = IOUtils.getFileLock(file, true);
if (lock == null)
return true;
lock.close();
return false;
} catch (IOException e) {
return true;
}
}
private void useFileChannel() throws IOException {
File file = File.createTempFile("j2objc", "tmp");
ChannelGetter channelGetter = new ChannelGetter();
channelGetter.createChannel(file);
// The FileOutputStream used to create the channel is released at this point.
FileChannel channel = channelGetter.get();
FileLock lock = channel.lock();
lock.close();
channel.close();
assertTrue(file.delete());
}
boolean isNotOpenByAnyProcess(@NotNull File file) {
try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel fileChannel = randomAccessFile.getChannel()) {
final FileLock fileLock = fileChannel.tryLock();
if (fileLock != null) {
fileLock.close();
return true;
}
} catch (IOException ignored) {
}
return false;
}