This article explains 5 methods to solve Java exclusive file writing, including some of your own understanding. If there is any inappropriateness, you are welcome to propose it.
Solution 1: Use RandomAccessFile 's file operation option s, s means writing in synchronization lock mode
RandomAccessFile file = new RandomAccessFile(file, "rws");
Solution 2: Use FileChannel 's 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 a shared lock, false is a exclusive lock if(fileLock!=null) break; else // There are other threads that occupy the lock sleep(1000);} Solution 3: First write the content to be written into a temporary file, and then change the name of the temporary file (Hack scheme uses 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(fileName) { // we may want to retry if move fails throw new IOException("Move failed"); } }} Solution 4: Encapsulate the file according to the file path and use synchronized to control the writing of the file
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(); } } Plan 5: A plan I came up with myself is not very accurate. By switching to set read and write permission control, simulate setting a writable marker (transformed into a classic read and write problem in the operating system...)
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(100); } catch(InteruptedException ie) { } // You can set a timeout write time} canWrite = false; // Now write file canWrite = true; }}The above is the solution to Java exclusively writing files. Have you learned it? You can refer to other articles to learn and understand it.