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 FileO
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
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 :)
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;
}
You can try this semaphore type code for a file lock by @ZZ Coder
File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
FileLock lock = channel.lock();
try {
lock = channel.tryLock();
// Ok. You get the lock
} catch (OverlappingFileLockException e) {
// File is open by someone else
} finally {
lock.release();
}
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.