How can I lock a file using java?

I have a java process that opens a file using a FileReader. How can I prevent another (java) process to open this file, or at least make that second process know that the file is already opened? Does this automaticaly makes the second process get an exception if the file is open(which solves my problem) or do i have to explicitly open it in the first process with some sort of flag or argument?

FileChannel.lock is probably what you want.

 

FileInputStream in = new FileInputStream(file);

try {

    java.nio.channels.FileLock lock = in.getChannel().lock();

    try {

        Reader reader = new InputStreamReader(in, charset);

        ...

    } finally {

        lock.release();

    }

} finally {

    in.close();

}

(Disclaimer: Code not compiled and certainly not tested.)

 

Note the section entitled "platform dependencies" in the API doc for FileLock