1. SRC. renameto (DEST) // rename a file or folder in Java. Similar to the MV command in Linux. Renaming is very important. For example, in the following scenario, a source synchronizes content to the target, and a thread blocks the content in the target. The precondition for processing is that the target content is completely synchronized before being processed.
This scenario is most suitable for renameto. First, rsync the source content to an intermediate folder, and then the folder in the middle of renameto is the target folder. The application only checks whether the target folder exists, it indicates that the content is complete. This method is better than directly synchronizing the source to the target. Due to the synchronization process, the application may read data incorrectly.
Import Java. io. file; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; public class testfile implements runnable {file; file file2; Public testfile () {try {executorservice exec = executors. newsinglethreadexecutor (); exec.exe cute (this); Exec. shutdown ();} catch (exception ex) {system. out. println (Ex) ;}} public void Init () {system. out. println ("Do some init "); File = new file ("/tmp/Middle"); file2 = new file ("/tmp/DEST");} public static void main (string [] ARGs) throws exception {// main is used to simulate MV operations in Linux. The main method can be improved to crontab to regularly execute the MV operation. Mv is as important as renameto !!! The same scenarios. // Linux: If the source does not exist, an error is returned. If the target path does not exist, it does not matter. It will be renamed according to the target path. // Windows: applications cannot rename folders. It is based on security and file indexing. // If DEST is null, NPE is thrown. testfile TF = new testfile (); TF. init (); system. out. println (TF. file. isdirectory () + "|" + TF. file2.isdirectory (); system. out. println (TF. file. renameto (TF. file2) ;}@ override public void run () {While (true) // block {try {// process thread every 1 s. sleep (1000); // If yes, start application processing. If (file2.exists () {// simulate an application to process data. Thread. Sleep (1000); // renameto is used to stop application processing. And exist. File2.renameto (File); system. Out. println ("the application processes the data. ") ;}} Catch (exception e) {e. printstacktrace ();}}}}