Reputation: 434
Can someone help me to check file is already in locked mode?
My program is unable to read the file because it is in locked mode, Then I re-create file again and my programme read file with no issue.
so is there any way to check file is already in locked mode?
Upvotes: 0
Views: 1816
Reputation: 412
The "research" suggested above gives no hint as to how to see if a file is locked. Method canWrite will return true even if the file is locked. What canWrite can do is to check to see if the directory is writable. If the directory and file are both writable but a write to the file fails, then the file is most likely locked.
My test code:
public static void main(String[]args){
File f = new File("junk.txt");
File dir = f.getAbsoluteFile().getParentFile();
System.out.println("can write dir " + dir.getName()+": "+dir.canWrite());
System.out.println("can write " + f.getName()+": "+f.canWrite());
try (Writer w = new FileWriter(f)) {
w.append("world\n");
System.out.println("write succeeded");
} catch (IOException ex) {
System.out.println("write failed");
}
}
In a test, I locked junk.txt by opening it in excel. When the file is locked, the output is
can write dir tools: true
can write junk.txt: true
write failed
When the file is not locked the write succeeds.
Upvotes: 1
Reputation: 865
Write to the file, if it fails, that means your file is locked.
File f = new File("suspiciousLockedFile.txt");
System.out.println(f.canWrite());
Upvotes: 0
Reputation: 406
Try to write to the file.It will be locked if you fail to write
or
try canWrite() java method from Java File API.
Refer: docs.oracle.com/javase/7/docs/api/java/io/File.html#canWrite()
Upvotes: 0