detect file is bein used by another process

Is there any way to check a file is being used by another process outside JVM ?Here is the problem that I run into it when trying to write over an existing file.

1.check if the file exists.

2.If it does, delete it.

3.Rewrite with the same file name.

The problem is if another process uses the same file, Java does not know, number 2 will return true but number 3 cant write to file since its being currently used. However Java still return true since number 2 was successful.

When the other process releases the file lock. The file gets deleted but not new file gets created.

Jay

[623 byte] By [jcoder2a] at [2007-11-27 11:19:04]
# 1

> When the other process releases the file lock

That's your answer, check for a file lock by trying to obtain a file lock on the file your self

File file = new File("somefile.txt");

try {

FileLock lock = lock = new FileOutputStream( lockFile ).getChannel().tryLock();

if(lock == null) {

JOptionPane.showMessageDialog(null, "File In use by another application");

return;

}

} catch(IOException ioe) {

ioe.printStackTrace();

return;

}

FileLock is found in java.nio.channels.

ICE

Message was edited by:

icewalker2g

icewalker2ga at 2007-7-29 14:34:38 > top of Java-index,Desktop,Core GUI APIs...
# 2

Thanks ICE. Its very helpful.

This forum is amazing. Java has to be successful just because this group of people.

jcoder2a at 2007-7-29 14:34:38 > top of Java-index,Desktop,Core GUI APIs...