This article illustrates the 5 ways to solve Java exclusive writing files, including some of their own understanding, if there is no place to welcome the proposed.
Scenario 1: Use the randomaccessfile file action option S,s to represent the synchronous lock mode write
Randomaccessfile file = new Randomaccessfile (file, "RWS");
Scenario 2: using the filechannel file lock
File File = new file ("Test.txt");
FileInputStream fis = new FileInputStream (file);
FileChannel channel = Fis.getchannel ();
Filelock filelock = null;
while (true) {
Filelock = channel.trylock (0, Long.max_value, false);//True means shared lock, false is exclusive lock
if (filelock!= NULL) break;
else //There are other threads occupying lock sleep
(1000);
}
Scenario 3: write the content first to a temporary file, and then rename the temporary file (hack scheme, using the principle of buffering + Atomic operation)
public class MyFile {
private String fileName;
Public MyFile (String fileName) {
this.filename = filename;
}
Public synchronized void WriteData (string data) throws IOException {
string tmpfilename = Uuid.randomuuid (). toString () + ". tmp";
File Tmpfile = new file (tmpfilename);
FileWriter FW = new FileWriter (tmpfile);
Fw.write (data);
Fw.flush ();
Fw.close ();
Now rename temp file to desired name, this operation is atomic operation under most OS
if (!tmpfile.renameto Me) {
//We may want to retry if move fails
throw new IOException (' Move failed ');
}
}
Scenario 4: encapsulating files based on file paths and using synchronized to control write files
public class MyFile {
private String fileName;
Public MyFile (String fileName) {
this.filename = filename;
}
Public synchronized void WriteData (String data) throws IOException {
FileWriter fw = new FileWriter (fileName);
Fw.write (data);
Fw.flush ();
Fw.close ();
}
Scenario 5: I think of a scheme that is not very precise. By switching settings read and Write permission control, the simulation set a writable mark (into the operating system of classic Read and write problems ...). )
public class MyFile {
private volatile Boolean canwrite = true;
Private String fileName;
Public MyFile (String fileName) {
this.filename = filename;
}
public void WriteData (String data) {while
(!canwrite) {
try {thread.sleep ()} catch (Interuptedexception IE) {}//can set a timeout write time
}
canwrite = false;
Now write file
canwrite = true;
}
The above is the Java exclusive write file solution, we have no learn, you can refer to other articles to learn understanding.