In a multi-threaded program, if a shared file is to be accessed or edited, how can I read and write files in the exclusive mode?
Using java. NiO. channels. filelock is a good method. The idea is to first create a file named genfile. LCK,
The getchannel (). trylock () method returns a filelock. If no one accesses the file, a reference not empty is returned,
If someone is accessing the service, null is returned,
In this way, the files being compiled by others will not be opened,
The Code is as follows:
Private Static final string gen_lck_file = "genfile. LCK ";
Private Static filelock genlock = NULL;
Public static void main (string ARGs []) {
Try {
// Acquire an exclusive lock, assure manager is stand alone
Genlock = new fileoutputstream (gen_lck_file). getchannel (). trylock ();
If (null! = Genlock ){
// Open the file you want!
} Else {
System. Err. println ("this file has been open but other person! ");
}
} Catch (filenotfoundexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
} Finally {
If (null! = Genlock ){
Try {
Genlock. Release ();
// Delete the lock file
New file (gen_lck_file). Delete ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
}
}
It is prompted that genfile. LCK only provides a locked file to determine whether the file is accessed. The file to be accessed is actually in the code.
// Open the file you want!
This line is processed!