How to determine whether a file is using?
A:
This question is about C# but i think it mostly applies to Java as well
Charlie boy
2009-05-20 05:52:08
+6
A:
In java you can lock Files and checking for shared access.
You can use a file lock to restrict access to a file from multiple processes
public class Locking {
public static void main(String arsg[])
throws IOException {
RandomAccessFile raf =
new RandomAccessFile("junk.dat", "rw");
FileChannel channel = raf.getChannel();
FileLock lock = channel.lock();
try {
System.out.println("Got lock!!!");
System.out.println("Press ENTER to continue");
System.in.read(new byte[10]);
} finally {
lock.release();
}
}
}
You also can check whether a lock exists by calling
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
Markus Lausberg
2009-05-20 05:57:13
+1 for `tryLock`.
Paul Morie
2009-05-21 15:26:25
A:
I think that what you're asking about is whether the file you're attempting to use is locked. You can use the FileLock
class to attempt to lock the file you're interested in. This class is intended to map to the native file-locking facility on the file system being used. If you can lock the file, it's safe to assume that no other process holds a lock on the file.
Paul Morie
2009-05-20 05:57:44
A:
Here is an easy Solution for Windows Users: http://www.dr-hoiby.com/WhoLockMe/
Tiny Tool but useful...
bastianneu
2009-05-20 07:09:09