Java stringbuffer read-write files
- Advantages of StringBuffer
- More string:string each update will be a new object , after the number of updates, the memory overhead is too high. While the StringBuffer type always has only one object in the process of updating (. Append, etc.), the overhead is greatly reduced.
- The member properties and member methods that are owned by the Stringbuilder:stringbuilder and StringBuffer classes are basically the same, except that the member method of the StringBuffer class is preceded by one more keyword:synchronized , needless to say, this keyword is secured during multi-threaded access, meaning that stringbuffer is thread -safe (so-called synchronized thread safety, which is when multiple threads are used, "lock" The same method of living an object/class, preventing multiple threads from accessing a method at the same time, creating a conflict, running an error. In-depth understanding, see
1 ImportJava.io.*;2 3 Public classFileio_stringbuffer {4 Public Static voidMain (string[] args) {5 //read files to StringBuffer6StringBuffer SB =NewStringBuffer ();7String SourcePath = "C:\\users\\administrator\\desktop\\1.txt";//source file Path (*. *)8BufferedReader br =NULL;9 Try {TenBR =NewBufferedReader (NewFileReader (SourcePath)); One String str; A while(str = br.readline ())! =NULL) {//read row by line -Sb.append (str);//add to StringBuffer tail -Sb.append ("\ r \ n");//line end plus line break the } -Br.close ();//don't forget, remember. - } - Catch(Exception e) { + System.out.println (E.getmessage ()); - } + A //Write File atString TargetPath = "C:\\users\\administrator\\desktop\\2.txt";//Destination file path -File f =NewFile (TargetPath);//New File - Try { -BufferedWriter BW =NewBufferedWriter (NewFileWriter (f)); - Bw.write (sb.tostring ()); - Bw.flush (); in bw.close (); - } to Catch(Exception e) { + System.out.println (E.getmessage ()); - } the } *}
Welcome Message Discussion!
Java stringbuffer read-write files