“This is the 10th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

The vast sea of thousands of thousands, thank you for this second you see here. Hope my article is helpful to you!

Wish you in the future, keep love, go to the mountains and seas!

Senior stream I/O

After our previous study, we are finished with some basic IO streams such as byte streams and character streams.

In the larger system of IO streams, in addition to the operation of basic streams, there are advanced streams waiting for us to unlock.

So without further discussion, today we’re going to look at one of these advanced streams — buffered streams.

Buffer flow

Buffered streams, also known as efficient streams, are enhancements to output and input streams.

Buffer flow classification

The fundamentals of buffering flows

When a stream object is created, a built-in buffer array of default size is created to reduce the number of system IO reads and writes through the buffer, thus improving the reading and writing efficiency.

Byte buffer stream

1. Construction method

  • public BufferedInputStream(InputStream in): Creates a new buffered input streamInputStreamType parameters.
  • Public BufferedOutputStream(OutputStream out) : creates a new BufferedOutputStream, passing an OutputStream parameter.

    Here is a demonstration:

    public class BufferedTest {
        public static void main(String[] args) throws FileNotFoundException {
            // Construct 1: create a byte buffered input stream.
            FileInputStream fps = new FileInputStream("e:\\demo\\b.txt");
            BufferedInputStream bis = new BufferedInputStream(fps);
    
            // Construct method 1: create a byte buffer input stream
            BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream("e:\\demo\\b.txt"));
    
            // Construct method 2: create byte buffer output stream
            FileOutputStream fos = new FileOutputStream("e:\\demo\\b.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
        
            // Construct method 2: create byte buffer output stream
            BufferedOutputStream bos2 = new BufferedOutputStream(new FileOutputStream("e:\\demo\\b.txt")); }}Copy the code

2. Feel productive

Since buffer flow is called efficient flow, we have to test whether it is a mule or a horse to pull out.

Get a feel for it:

public class BufferedTest2 {
    public static void main(String[] args) {
        // Use multiple threads to test the replication speed of both.
        new Thread(() -> oldCopy()).start();// This is a Lambda expression in the new JDK8 feature
        new Thread(() -> bufferedCopy()).start();
        
        New Thread(new Runnable() {@override public void run() {oldCopy(); } }).start(); * /
    }

    public static void oldCopy(a) {
        // Record the start time
        long start = System.currentTimeMillis();
        // Create a stream object
        try (
                FileInputStream fis = new FileInputStream("E :\\demo\\ Kobe's speech.MP4");
                FileOutputStream fos = new FileOutputStream("e:\\demoCopy\\oldCopy.mp4")
        ){
            // Read and write data
            int b;
            while((b = fis.read()) ! = -1) { fos.write(b); }}catch (IOException e) {
            e.printStackTrace();
        }
        // Record the end time
        long end = System.currentTimeMillis();
        System.out.println("Normal stream replication time :"+(end - start)+"Ms");
    }

    public static void bufferedCopy(a) {
        // Record the start time
        long start = System.currentTimeMillis();
        // Create a stream object
        try (
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E :\\demo\\ Kobe's speech.MP4"));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("e:\\demoCopy\\newCopy.mp4")); {// Read and write data
            int b;
            while((b = bis.read()) ! = -1) { bos.write(b); }}catch (IOException e) {
            e.printStackTrace();
        }
        // Record the end time
        long end = System.currentTimeMillis();
        System.out.println("Buffer stream replication time :"+(end - start)+"Ms"); }} Run result: buffer stream replication time:3498Ms normal stream replication time:319839msCopy the code

After the program runs, you can deeply experience the fast buffer flow, the buffer flow has been copied successfully, but the normal flow has not succeeded. Not only did it not work, it took forever. You can feel that the buffered flow is dozens of times larger than the normal flow. This video is only 46.2m in size. What about a larger file, a few hundred megabytes or even a few gigabytes? I won’t be able to complete the transmission all day. Isn’t this very Baidu network disk?

Feel not fast enough, want to experience the general feeling of flying. Now I’ll take you to the top of the clouds. Hey hey, old driver wants to drive, don’t get carsick.

Next, use an array to experience:

public class BufferedTest3 {
    public static void main(String[] args) {
    // Use multiple threads to test the replication speed of both.
        new Thread(() -> oldCopy()).start();
        new Thread(() -> bufferedCopy()).start();

    }

    public static void oldCopy(a) {
        // Start time
        long start = System.currentTimeMillis();

        try(
                FileInputStream fis = new FileInputStream("E :\\demo\\ Kobe's speech.MP4");
                FileOutputStream fos = new FileOutputStream("e:\\demoCopy\\oldCopy2.mp4"); {int len;
            byte[] b = new byte[1024];
            while((len = fis.read(b)) ! = -1) {
                fos.write(b, 0, len); }}catch (IOException e) {
            e.printStackTrace();
        }

        // End time
        long end = System.currentTimeMillis();
        System.out.println("Normal stream array copy time:" + (end - start) + "毫秒");
    }

    public static void bufferedCopy(a) {
        // Start time
        long start = System.currentTimeMillis();
        // Create a stream object
        try (
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E :\\demo\\ Kobe's speech.MP4"));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("e:\\demoCopy\\newCopy2.mp4")); {// Read and write data
            int len;
            byte[] bytes = new byte[1024];
            while((len = bis.read(bytes)) ! = -1) {
                bos.write(bytes, 0, len); }}catch (IOException e) {
            e.printStackTrace();
        }
        // End time
        long end = System.currentTimeMillis();
        System.out.println("Buffer stream using array copy time :"+(end - start)+"Ms"); }} program execution result: buffer stream using array copy time:370Ms normal stream array copy time:1016msCopy the code

If not, you can change byte[] bytes = new byte[1024] to byte[] bytes = new byte[1024*8]. It allows you to experience more efficiency. You’ll feel the speed go through the air.

Character buffer stream

1. Construction method

  • Public BufferedReader(Reader in) : Creates a new bufferedinput stream, passing in arguments of type Reader.

  • Public BufferedWriter(Writer out) : Creates a new BufferedWriter(Writer out) stream, passing in parameters of type Writer.

    Here is a demonstration:

    // Create a character buffered input stream
    BufferedReader br = new BufferedReader(new FileReader("e:\\demo\\b.txt"));
    // Create a character buffer output stream
    BufferedWriter bw = new BufferedWriter(new FileWriter("e:\\demo\\b.txt"));
    Copy the code

2. Special methods

Instead of using byte buffer streams and character streams, he has something that no one else has. What is that? Let’s look at it now:

  • BufferedReader: public String readLine(): reads a line of text and returns NULL if it reaches the end.

  • Character buffering output stream BufferedWriter: public void newLine(): Writes line delimiters, or newlines, defined by system properties.

    Step by step:

    1. Public void newLine () :

      public class BufferedTest4 {
          public static void main(String[] args) throws IOException {
              BufferedWriter bw = new BufferedWriter(new FileWriter("e:\\demo\\hello.txt"));
      
              // Write the data
              bw.write("Hello");
              / / a newline
              //public void newLine()
              bw.newLine();
              bw.write("world");
              bw.newLine();
              bw.write("Java");
              bw.newLine();
              bw.write("newLine"); bw.flush(); bw.close(); }} After the program is executed, check the hello. TXT information: Hello world Java newLineCopy the code
    2. public String readLine():

      public class BufferedTest5 {
          public static void main(String[] args) throws IOException {
              BufferedReader br = new BufferedReader(new FileReader("e:\\demo\\hello.txt"));
      
              // Define to get the string
              String line = null;
              while((line = br.readLine()) ! =null) { System.out.println(line); } br.close(); }} After the program is executed, check the hello. TXT information: Hello world Java newLineCopy the code

Text sorting case

What is the text sorting exercise? Here I share one of my favorites, and then arrange it in a certain order. Of course don’t worry, there must be a way you can reorder.

8.Since the goal is the horizon7.I don't want to think behind will hit the cold wind and rain3.Then only trials and hardships9.What I can leave on the world is only their view of my back4.I don't think about winning love5.Since I love roses6.Be brave enough to tell the truth10.I don't think about the future is flat or muddy11.As long as you love life12.It was all as expected5.Since I love roses6.Be brave enough to tell the truth1.I don't think about whether I can succeed or not2.Since the choice of the distanceCopy the code

“Love life” comes from wang Guozhen’s poetry collection. To tell you the truth, THIS article has been quoted by me in my high school composition. Not only this one, but also Wang Guozhen’s “Thank you” and so on. Although the composition has not been particularly high scores, but also can not hinder my love for Wang Guozhen’s works. As I wanted to harvest a wisp of spring breeze, but you gave me the whole summer. You have to trust that your talents won’t be buried forever. So when we cross a mountain, we also cross a true self.

Okay, Stop, back to the point: how do we order this poem?

Analysis:

  • We just learned to read a line in a character buffer stream, so we can read each line first.

  • And then you don’t have to parse the text, so we use the first row or two? But if I have a lot of text, and I have hundreds of lines, and I have three digits, that’s not a good way to display it.

  • We should see the character “.” after the serial number, and we can start with this defect. Then the split sequence number and text are stored in the set, which has CP combination, we can use the Map set.

  • Then the sorted text will be written back into the file.

  • OK, now that we know the idea, let’s do it together:

    public class BufferedTest6 {
        public static void main(String[] args) throws IOException {
            // Create a character input stream object
            BufferedReader br = new BufferedReader(new FileReader("E :\\demo\\ love life.txt"));
    
            // Create a character output stream object
            BufferedWriter bw = new BufferedWriter(new FileWriter("E :\\demoCopy\\ love life.txt"));
    
            // Create a set of maps to store future data, with keys as sequence numbers and values as text.
            HashMap<String, String> map = new HashMap<>();
    
            // Read the data
            String line = null;
            while((line = br.readLine()) ! =null) {
                // Split text and number by
                String[] split = line.split("\ \.");
                // Store the obtained data in the collection
                map.put(split[0], split[1]);
            }
    
            // The next step is to get the text by finding the value by the ordinal number or key
            for (int i = 1; i <= map.size(); i++) {
                String key = String.valueOf(i);
                / / key values
                String value = map.get(key);
    
                // After getting the text, I still write the serial number in here. If you believe my classmates, you don't need to write the serial number.
                bw.write(key + "." + value);
                if(i == 7){
                    System.out.println(value);
                }
                //bw.write(value);
                bw.newLine();
                bw.flush();
            }
            bw.flush();
            // Release resourcesbw.close(); br.close(); }}Copy the code

    After the program runs, just as everything is expected, look at the file to see:

    1.I don't think about whether I can succeed or not2.Since the choice of the distance3.Then only trials and hardships4.I don't think about winning love5.Since I love roses6.Be brave enough to tell the truth7.I don't want to think behind will hit the cold wind and rain8.Since the goal is the horizon9.What I can leave on the world is only their view of my back10.I don't think about the future is flat or muddy11.As long as you love life12.It was all as expectedCopy the code

    If you do not want the order number, you can choose not to write the ordinal number.

conclusion

I believe that you have a certain understanding of IO streams in advanced streams buffer flow class, looking forward to the next chapter of advanced streams – transformation streams teaching!

Of course, there are many streams waiting to watch together next time! Welcome to the next chapter!

So far, the world is closed for today, good night! Although this article is over, BUT I still, never finished. I will try to keep writing articles. The coming days are long, and the horse is slow!

Thank you for seeing this! May you be young and have no regrets!

Note: If there are any mistakes and suggestions, please leave a message! If this article is also helpful to you, I hope you give a lovely and kind attention, thank you very much!