How to check if a file is open by another process (Java/Linux)?
Solution 1
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.
Solution 2
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 :)
Solution 3
This one should also work for Windows systems. But attention, does not work for Linux!
private boolean isFileClosed(File file) {
boolean closed;
Channel channel = null;
try {
channel = new RandomAccessFile(file, "rw").getChannel();
closed = true;
} catch(Exception ex) {
closed = false;
} finally {
if(channel!=null) {
try {
channel.close();
} catch (IOException ex) {
// exception handling
}
}
}
return closed;
}
Solution 4
Thanks for the original suggestion. I have one small upgrade that is somewhat important to that method:
FileOutputStream fos = null;
try {
// Make sure that the output stream is in Append mode. Otherwise you will
// truncate your file, which probably isn't what you want to do :-)
fos = new FileOutputStream(file, true);
// -> file was closed
} catch(IOException e) {
// -> file still open
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Cheers, Gumbatron
![salocinx](https://i.stack.imgur.com/pUCYm.jpg?s=256&g=1)
salocinx
Updated on May 31, 2020Comments
-
salocinx about 4 years
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 :-)