小智 23
使用Apache Commons IO库......
boolean isFileUnlocked = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
isFileUnlocked = true;
} catch (IOException e) {
isFileUnlocked = false;
}
if(isFileUnlocked){
// Do stuff you need to do with a file that is NOT locked.
} else {
// Do stuff you need to do with a file that IS locked
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*n C 13
(Q&A是关于如何处理Windows"打开文件"锁...而不是如何实现这种可锁定的锁定.)
整个问题充满了可移植性问题和竞争条件:
FileLock或其他东西,您仍然遇到可能出现问题的问题,并在您测试文件和重命名之间打开文件.一个更简单但不可移植的解决方案是尝试重命名(或者您正在尝试做的任何事情)并诊断返回值和/或由于打开的文件而产生的任何Java异常.
笔记:
如果您使用FilesAPI而不是FileAPI,则会在发生故障时获得更多信息.
在允许重命名锁定或打开文件的系统(例如Linux)上,您不会得到任何失败结果或异常.该操作将成功.但是,在这样的系统上,您通常不必担心文件是否已打开,因为操作系统不会在打开时锁定文件.
// TO CHECK WHETHER A FILE IS OPENED
// OR NOT (not for .txt files)
// the file we want to check
String fileName = "C:\\Text.xlsx";
File file = new File(fileName);
// try to rename the file with the same name
File sameFileName = new File(fileName);
if(file.renameTo(sameFileName)){
// if the file is renamed
System.out.println("file is closed");
}else{
// if the file didnt accept the renaming operation
System.out.println("file is opened");
}
Run Code Online (Sandbox Code Playgroud)
在Windows上我找到了答案/sf/answers/959488071/使用
fileIsLocked = !file.renameTo(file)
最有用,因为它在处理写保护(或只读)文件时避免了误报。
我认为您永远不会为此获得明确的解决方案,操作系统不一定会告诉您文件是否打开。
java.nio.channels.FileLock尽管 javadoc 充满了警告,但您可能会从 中得到一些好处。