For example, filereader and filewriter send requests to the disk once or once when reading data. This process takes a very long time and has a low efficiency, therefore, bufferedreader and bufferedwriter are introduced as the cache for reading and writing data.
1. bufferedreader reads 8 K of bytes into the memory at a time. When the program reads characters, it first reads them from bufferedreader. If not, bufferedreader reads the data from the disk again, and the data is 8 K at a time.
2. bufferedwriter is used as the write cache, and the volume stream of the file to be written into bufferedwriter (in memory) is written to the disk only when bufferedwriter is refreshed or disabled. This reduces the number of disk writes and improves efficiency.
When using these two methods, you must first have a stream object. The code example is as follows:
Import Java. io. *; Class test {public static void main (string [] ARGs) {try {copy ("C: \ log.txt", "d: \ testlog.txt ");} catch (ioexception e) {e. printstacktrace (); system. out. println ("Io exception") ;}} public static void copy (string sourcepath, string destpath) throws ioexception {// create read and write buffer bufferedreader = new bufferedreader (New filereader (sourcepath); bufferedwriter = ne W bufferedwriter (New filewriter (destpath, true); // It is used to store a row read by bufferedreader. String readercache = NULL; // It is determined by a line break when bufferedreader reads a row, but it does not read the linefeed while (readercache = bufferedreader. readline ())! = NULL) {bufferedwriter. write (readercache); bufferedwriter. newline (); // write a linefeed bufferedwriter. flush (); // refresh the written file} // when the buffer zone is closed, the stream resource is closed.
// Pay attention to the judgment when closing the resource. If it is not successfully created, it is null. If it is disabled, an exception will occur, enhancing the robustness of the Code.
If (bufferedreader! = NULL) bufferedreader. Close ();
If (bufferedwriter! = NULL) bufferedwriter. Close ();}}
Io stream-read write buffer