Sometimes the following message is displayed when you open a file: the file has beenProgramUsage. Opening failed. This is because another program is editing the file and does not want other programs to modify the file during the editing process, thus locking the file.
In Java, the filelock class is used to lock files.CodeThis method is demonstrated.
Package fileoperation; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. NIO. channels. filelock; public class lockfile {public static void main (string [] ARGs) throws ioexception {fileoutputstream fous = NULL; filelock = NULL; try {fous = new fileoutputstream ("C: \ file_lock.txt "); filelock = fous. getchannel (). trylock (); // method for obtaining the Lock Object. // This thread is locked for one minute. No other program can perform write operations on the object within one minute. thread. sleep (60 * 1000);} catch (exception e) {e. printstacktrace ();} finally {If (filelock! = NULL) filelock. Release (); If (fous! = NULL) fous. Close ();}}}