tags:

views:

333

answers:

5

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
A: 

I don't think that Java can tell you whether another process is using a file. Depending on what you're trying to do, you might get an IOException when you try to manipulate it. Otherwise, if you're no Linux, you might want to look at lsof.

albertb
+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
+1 for `tryLock`.
Paul Morie
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
A: 

Here is an easy Solution for Windows Users: http://www.dr-hoiby.com/WhoLockMe/

Tiny Tool but useful...

bastianneu