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 :-)
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.
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.
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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With