Buffer stream of IO stream

Posted by ardyandkari on Fri, 12 Jun 2020 06:15:55 +0200

Article catalog

Buffer stream of IO stream

Buffer stream is a more powerful stream, which can read and write efficiently. In addition, there are transformation streams that can transform encoding, serialization streams that can persist storage objects, and so on. These more powerful flows are created on the basis of basic flow objects, which is equivalent to an enhancement of basic flow objects.

Compared with the ordinary stream, the buffer stream reads and writes 8192 bytes by default at a time. When the ordinary stream reads through an array, it can be more efficient than the buffer stream by setting the appropriate number byte length. However, the buffer stream can also change the default value of the buffer zone and the number of bytes handled each time, making the buffer stream more flexible.

1. Overview of buffer flow

Buffer stream is an enhancement of FileOutputStream/FileInputStream/FileWriter/FileReader stream, so it is also four streams, classified by data type:

  1. Byte buffer stream: BufferedInputStream/BufferedOutputStream
  2. Character buffer stream: BufferedReader/BufferedWriter

The basic principle of buffer flow is to create a built-in buffer array of default size when creating a stream object, read and write through the buffer, and write to the disk once when the buffer size is enough, so as to reduce the number of system IO, so as to improve the efficiency of reading and writing.
When learning the basic flow, we already know the two methods: flush() and close(). Here's another point:

  1. flush() writes out the file from the buffer.
  2. close() writes the file out of the buffer and closes the corresponding stream.

2. Byte buffer stream

BufferedInputStream/BufferedOutputStream

Construction method

  • public BufferedInputStream(InputStream in): creates a new buffered input stream.
  • public BufferedOutputStream(OutputStream out): creates a new buffered output stream.
// Create byte buffered input stream
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));
// Create byte buffered output stream
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));
Efficiency test

Query API, buffer stream read-write method is consistent with the basic stream, we test its efficiency by copying large files.

Using the basic flow, the code is as follows:

public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // Record start time
        long start = System.currentTimeMillis();
        // Create a flow object
        try (
            FileInputStream fis = new FileInputStream("jdk9.exe");
            FileOutputStream fos = new FileOutputStream("copy.exe")
        ){
            // Read and write data
            int b;
            while ((b = fis.read()) !=1) {
                fos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Record end time
        long end = System.currentTimeMillis();
        System.out.println("Normal stream copy time:"+(end ‐ start)+" millisecond");
    }
}

Ten minutes later

Using the buffer stream, the code is as follows:

public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // Record start time
        long start = System.currentTimeMillis();
        // Create a flow object
        try (
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
        ){
            // Read and write data
            int b;
            while ((b = bis.read()) !=1) {
                bos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Record end time
        long end = System.currentTimeMillis();
        System.out.println("Buffer stream copy time:"+(end ‐ start)+" millisecond");
    }
}

Buffer stream copy time: 8016 MS

How can it be faster?

Using array, the code is as follows:

public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // Record start time
        long start = System.currentTimeMillis();
        // Create a flow object
        try (
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
        ){
            // Read and write data
            int len;
            byte[] bytes = new byte[8*1024];
            while ((len = bis.read(bytes)) !=1) {
                bos.write(bytes, 0 , len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Record end time
        long end = System.currentTimeMillis();
        // Buffer stream use array copy time: 666 MS
        System.out.println("Buffer stream uses array copy time:"+(end ‐ start)+" millisecond");
    }
}

3. Character buffer stream

Construction method

public BufferedReader(Reader in): creates a new buffered input stream.

public BufferedWriter(Writer out): creates a new buffered output stream.

// Create byte buffered input stream
BufferedReader br = new BufferedReader(new FileReader("br.txt"));
// Create byte buffered output stream
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
Unique methods

The basic methods of character buffer stream are the same as those of ordinary character stream calls. We will not elaborate any more. Let's see their unique methods.

Bu "eredReader: public String readLine(): read a line of text.

public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
        // Create a flow object
        BufferedReader br = new BufferedReader(new FileReader("in.txt"));
        // Define string, save the read line of text
        String line = null;
        // Loop read, read to the last return null
        while ((line = br.readLine())!=null) {
            System.out.print(line);
            System.out.println("‐‐‐‐‐‐");
        }
        // Release resources
        br.close();
    }
}

Bu "eredWriter: public void newLine(): write a line separator, which is defined by the system property.

public class BufferedWriterDemo throws IOException {
    public static void main(String[] args) throws IOException {
        // Create a flow object
        BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
        // Write data
        bw.write("Simple dimension");
        // Write new line
        bw.newLine();
        bw.write("program");
        bw.newLine();
        bw.write("member");
        bw.newLine();
        // Release resources
        bw.close();
    }
}
//Output effect:
//Simple dimension
//program
//member

4. Exercise - text sorting

Please restore the text information order

3. The squire, servant Guo Youzhi, Fei Yi, Dong Yun, etc. are all good and practical. They are determined to be loyal and pure. They leave their majesty with the help of the emperor. It is foolish to think that there is no big or small thing in the palace, and to know and consult it, and then to carry it out, it will be beneficial to fill the gaps and omissions.

8. May your majesty entrust his ministers with the purpose of appealing to thieves to revive the effect. If it fails to do so, he will punish his ministers and accuse the spirit of the previous emperor. If there is no words of morality, you should be responsible for the slowness of your deeds, your deeds, and your permission, so as to show your guilt. Your majesty should also make his own plans, and take care of the good ways of the Suwa and the elegant words, so as to catch up with the imperial edicts of the previous emperor. I am grateful for your kindness.

4. General Xiang Chong, Xing Shujun, Xiaochang military, tried to use it in the past. The first emperor called it "NENG", which was supervised by people's opinions. It is foolish to think that if you know what is going on in the camp and consult with them, you will be able to bring peace to the battle line and gain advantages and disadvantages.

2. In the palace, they are all in one. It's not suitable for similarities and differences. If there are those who commit crimes and are loyal to the good, it is advisable to pay the punishment and reward of those who are discussed by the Secretary, so as to show his Majesty's justice, not to be partial, and to make the internal and external laws different.

1. Before the founding of the first emperor, the middle road collapsed. Today, in the next three points, Yizhou is suffering from weakness. This is a critical autumn. However, the ministers of the bodyguard are unremitting in the interior, and the loyal and determined people forget to be outside. They cover the special encounter of chasing the first emperor and want to report it to his majesty. It's better to be open to the public and listen to them. It's better to inherit virtue from the emperor, to be ambitious and ambitious. It's better not to belittle yourself, to misinterpret words, and to stop the road of loyal advice.

9. Stay away from me now. I don't know what to say.

6. The minister is the one who sets up his clothes, works in Nanyang, lives in troubled times, and doesn't ask for information. The first Emperor didn't mean his officials to be despicable, and he perverted himself. Three times, he considered his officials in the grass. He was grateful for the current affairs of his officials, so he allowed the first emperor to drive away. After the fall of the value, when he was appointed to the defeat of the army, he was ordered to be in danger. I have been here for 20 years.

7. The first emperor knew that his officials were cautious, so he sent his officials to deal with major issues in the face of collapse. Since I was ordered, I've been worried all night. I'm afraid that the trust will not work. I hurt the Ming Dynasty of the former Emperor, so I crossed Lu in May and went deep. Today, the South has been determined, and the armour has been sufficient. When the three armies are awarded, the north is determined to be the Central Plains. The commoners are exhausted and dull. They hustle out the traitors, revive the Han Dynasty, and return to the old capital. This minister therefore reported to the first emperor and was loyal to his majesty. As for the consideration of profit and loss, if we make full use of our loyalty, we will be responsible for your, your, and your permission.

5. Qin Xianchen, Yuan Xiaoren, the former Han Dynasty prospered; Qin Xiaoren, Yuan Xianchen, later Han Dynasty declined. When the first emperor was there, every time he talked about this with his officials, he did not fail to sigh and hate Yu Huan and Ling Yi. The attendants, ministers, long history, and soldiers, who have learned about the purity, the good, and the dead, wish their majesty to believe them, then the prosperity of the Han Dynasty can be counted on a day.

case analysis
  1. Read the text line by line.

  2. Parse text information into the collection.

  3. Traverse the set, write out the text information in order.

Case realization
public class BufferedTest {
    public static void main(String[] args) throws IOException {
        // Create map set, save text data, key as sequence number, value as text
        HashMap<String, String> lineMap = new HashMap<>();
        // Create a flow object
        BufferedReader br = new BufferedReader(new FileReader("in.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
        // Read data
        String line = null;
        while ((line = br.readLine())!=null) {
            // Parse text
            String[] split = line.split("\\.");
            // Save to collection
            lineMap.put(split[0],split[1]);
        }
        // Release resources
        br.close();
        // Traversal map set
        for (int i = 1; i <= lineMap.size(); i++) {
            String key = String.valueOf(i);
            // Get text in map
            String value = lineMap.get(key);
            // Write splicing text
            bw.write(key+"."+value);
            // Write new line
            bw.newLine();
        }
        // Release resources
        bw.close();
    }
}

Topics: encoding