Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if file is in use by another process (Java)

I have tried many examples, but no one works. I try this but don't work.

I tried also to use the tryLock(). It always returns false. why?

private boolean checkCompleteFile(File f)
{           
    RandomAccessFile file = null;
    FileLock fileLock = null;

    try
    {
        file = new RandomAccessFile(f, "rw");
        FileChannel fileChannel = file.getChannel();

        fileLock = fileChannel.lock();
        if (fileLock != null)
        {
            fileLock.release();
            file.close();
            return false;
        }

    }
    catch(Exception e)
    {
         return false;
    }

    return true;
}
like image 691
Emanuele Mazzoni Avatar asked Apr 15 '13 08:04

Emanuele Mazzoni


People also ask

How do you check if the file is being used by another process in Java?

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.

How can I tell if a file is being used by another process?

Just run that (maybe you need to launch it with administrator rights), hit Ctrl-F and type in the name of the file which is locked - it will find all open handles which match the given name, and tell you which process it belongs to.

How do you check if a file does not exist in Java?

To test to see if a file or directory exists, use the “ exists() ” method of the Java java. io. File class. If the exists() method returns true then the file or directory does exist and otherwise does not exists.


3 Answers

You catch an exception and return false, thats why you get false all the time, do something with the exception or do not catch it so you know if an exception was thrown, if you catch a general exception a false return value is not really meaningful.

try {
  lock = channel.tryLock();
  // ...
} catch (OverlappingFileLockException e) {
  // File is already locked in this thread or virtual machine
}
lock.release();
channel.close();

You cam just try to access the file and catch an exception if it fails:

boolean isLocked=false;
RandomAccessFile fos=null;
try {
      File file = new File(filename);
      if(file.exists())
        fos=new RandomAccessFile(file,"rw");        
}catch (FileNotFoundException e) {
    isLocked = true;
}catch (SecurityException e) {
    isLocked = true;
}catch (Exception e) {
    // handle exception
}finally {
    try {
        if(fos!=null) {
            fos.close();
        }
    }catch(Exception e) {
        //handle exception
    }
}

Notice that the RandomAccessFile class throws:

FileNotFoundException -

if the mode is "r" but the given string does not denote an existing regular file, or if the mode begins with "rw" but the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file.

SecurityException -

if a security manager exists and its checkRead method denies read access to the file or the mode is "rw" and the security manager's checkWrite method denies write access to the file

like image 140
CloudyMarble Avatar answered Oct 01 '22 23:10

CloudyMarble


Try using this:

try {
    @SuppressWarnings("resource")
    FileChannel channel = new RandomAccessFile(fileToRead, "rw").getChannel();
    //This method blocks until it can retrieve the lock. 
    FileLock lock = channel.lock(); // Try acquiring the lock without blocking. 
    try { 
        lock = channel.tryLock();
    } catch (OverlappingFileLockException e){

    }
    lock.release(); //close the file.
    channel.close();
} catch (Exception e) {             

}
like image 28
StarCrafter Avatar answered Oct 01 '22 22:10

StarCrafter


How about using the linux command ?

lsof -p 

The command will show the file open status, you can parse it to check who use it.

like image 28
qrtt1 Avatar answered Oct 02 '22 00:10

qrtt1