我有一个文件夹中的文件列表, 我想锁定一个特定的文件(用户向我发送要锁定的文件的名称),我正在执行以下操作:
try {
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = channel.lock();
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked
}
} catch (Exception e) {
}
如果另一个用户想要查看文件列表,我必须告诉他们哪些文件已锁定,哪些文件已解锁
File folder = new File("E:\\folder_to_LIST_OF_FILES");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
FilesDto returnDto = new FilesDto();
returnDto.setFileName(FilenameUtils.removeExtension(listOfFiles[i].getName()));
// Check File Status if file is Locked or unlocked
if (lock==null) {
returnDto.setStatus("unlocked");
returnDto.setFilePath(listOfFiles[i].getAbsolutePath());
} else {
returnDto.setStatus("Locked");
}
returnDtoList.add(returnDto);
}
}
这两个片段来自不同的 API。 如何检查文件的状态是锁定还是解锁?
最佳答案
documentation在 FileLock 类上说:
This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.
所以看来您可以使用与第一个片段中相同的代码:
File folder = new File("E:\\folder_to_LIST_OF_FILES");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
FilesDto returnDto = new FilesDto();
returnDto.setFileName(FilenameUtils.removeExtension(listOfFiles[i].getName()));
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock;
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked
}
if (lock==null) {
returnDto.setStatus("unlocked");
returnDto.setFilePath(listOfFiles[i].getAbsolutePath());
} else {
lock.release();
returnDto.setStatus("Locked");
}
returnDtoList.add(returnDto);
}
}
关于java - java中的文件锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51743831/