Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file is open by another process (Java/Linux)?

Tags:

java

file

linux

I am trying to check if a certain java.io.File is open by an external program. On windows I use this simple trick:

try {     FileOutputStream fos = new FileOutputStream(file);     // -> file was closed } catch(IOException e) {     // -> file still open } 

I know that unix based systems allow to open files in multiple processes... Is there a similar trick to achieve the same result for unix based systems ?

Any help / hack highly appreciated :-)

like image 971
salocinx Avatar asked Feb 18 '12 13:02

salocinx


People also ask

How do you check if a file is open by another process in Java?

You can run from Java program the lsof Unix utility that tells you which process is using a file, then analyse its output. To run a program from Java code, use, for example, Runtime , Process , ProcessBuilder classes.

How do you check if a file is open by another process Linux?

The command lsof -t filename shows the IDs of all processes that have the particular file opened. lsof -t filename | wc -w gives you the number of processes currently accessing the file.

How do you identify the file is used by another process?

Just run that (maybe you need to launch it with administrator rights), hit Ctrl-F and type in the name of the file which is locked - it will find all open handles which match the given name, and tell you which process it belongs to.


2 Answers

Here's a sample how to use lsof for unix based systems:

public static boolean isFileClosed(File file) {     try {         Process plsof = new ProcessBuilder(new String[]{"lsof", "|", "grep", file.getAbsolutePath()}).start();         BufferedReader reader = new BufferedReader(new InputStreamReader(plsof.getInputStream()));         String line;         while((line=reader.readLine())!=null) {             if(line.contains(file.getAbsolutePath())) {                                             reader.close();                 plsof.destroy();                 return false;             }         }     } catch(Exception ex) {         // TODO: handle exception ...     }     reader.close();     plsof.destroy();     return true; } 

Hope this helps.

like image 80
Hans Frankenstein Avatar answered Sep 28 '22 14:09

Hans Frankenstein


You can run from Java program the lsof Unix utility that tells you which process is using a file, then analyse its output. To run a program from Java code, use, for example, Runtime, Process, ProcessBuilder classes. Note: your Java program won't be portable in this case, contradicting the portability concept, so think twice whether you really need this :)

like image 27
Alexey Berezkin Avatar answered Sep 28 '22 13:09

Alexey Berezkin