Reputation: 5354
There is some API that allows checking if a file is locked or opened by another program, so my process cannot write to that file.
e.g. we can use this:
File f = new File("some-locked-file.txt");
System.out.println(f.canWrite()); // -> true
new FileOutputStream(f); // -> throws a FileNotFoundException
But there is no guarantee this will work in 100% of cases.
For instance, on my Windows machine if I'm trying to check .csv
file, it works as expected - when I open .csv
file by another program, my Java code will throw FileNotFoundException
, but there is no exception for plain .txt
file opened with simple Notepad.
Is there any easy way to check if a file is locked with 100% sureness?
Upvotes: 1
Views: 1566
Reputation: 14668
This turned out to be an interesting question and I tried a couple of things myself and below are my observations:
java.io.FileNotFoundException: C:\E_Drive\him.csv (The process cannot access the file because it is being used by another process)
will not thrown or not will depend upon the editor which has opened the file. new FileOutputStream(file);
will not throw the exception but if you open same txt file from an excel then new FileOutputStream(file);
throw the exception.So, I think really answer to your question is "it depends".
Upvotes: 1