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?