ikos23
ikos23

Reputation: 5354

How to check if file is locked (opened by some other app)

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?

My program exec example.

Upvotes: 1

Views: 1566

Answers (1)

hagrawal7777
hagrawal7777

Reputation: 14668

This turned out to be an interesting question and I tried a couple of things myself and below are my observations:

  • Whether 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.
  • If you open a txt file in notepad/notepad++ then 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.
  • My best guess is that probably with software like excel, excel will lock the file and indicate the same to OS and so OS indicate the same to JVM and hence JVM throws the exception, but this doesn't happen with software like notepad/notepad++.

So, I think really answer to your question is "it depends".

Upvotes: 1

Related Questions