The seventh day of super hard core detailed learning series - the knowledge points of IO in simple terms are worth learning and collecting

I/O advanced flow

After our previous study, we have learned some basic streams of IO stream, such as byte stream and character stream.

In the whole system of IO streams, in addition to some basic stream operations, he also has some advanced streams waiting for us to unlock.

So I won't say much. Today, let's learn one of the high-level streams - buffer stream.

Buffer stream

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

Classification of buffer streams

Basic principle of buffer flow

When creating a stream object, a built-in buffer array of default size will be created to reduce the number of system IO through buffer reading and writing, so as to improve the efficiency of reading and writing.

Byte buffer stream

1. Construction method

  • public BufferedInputStream(InputStream in): to create a new buffered input stream, you need to pass in an InputStream type parameter.
  • public BufferedOutputStream(OutputStream out): to create a new buffered output stream, you need to pass in an OutputStream type parameter.

    The demonstration is as follows:

    public class BufferedTest {
        public static void main(String[] args) throws FileNotFoundException {
            //Construction method 1: create byte buffered input stream [but the following format declaration is commonly used in development]
            FileInputStream fps = new FileInputStream("e:\\demo\\b.txt");
            BufferedInputStream bis = new BufferedInputStream(fps);
    
            //Construction method 1: create byte buffered input stream
            BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream("e:\\demo\\b.txt"));
    
            //Construction mode 2: create byte buffered output stream
            FileOutputStream fos = new FileOutputStream("e:\\demo\\b.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
        
            //Construction mode 2: create byte buffered output stream
            BufferedOutputStream bos2 = new BufferedOutputStream(new FileOutputStream("e:\\demo\\b.txt"));
        }
    }
    Copy code

2. Feel efficient

Since the buffer flow is called efficient flow, we have to test it. It's a mule or a horse that pulls it out.

Let's feel it first:

public class BufferedTest2 {
    public static void main(String[] args) {
        //Use multithreading to test the replication speed of both at the same time.
        new Thread(() -> oldCopy()).start();//This is the Lambda expression in the new feature of JDK8
        new Thread(() -> bufferedCopy()).start();
        
        /*
           As is equivalent to:
           new Thread(new Runnable() {
                @Override
                public void run() {
                    oldCopy();
                }
            }).start();
         */
    }

    public static void oldCopy() {
        // Record start time
        long start = System.currentTimeMillis();
        // Create flow object
        try (
                FileInputStream fis = new FileInputStream("e:\\demo\\Kobe Bryant'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 end time
        long end = System.currentTimeMillis();
        System.out.println("Normal stream replication time:"+(end - start)+" millisecond");
    }

    public static void bufferedCopy() {
        // Record start time
        long start = System.currentTimeMillis();
        // Create flow object
        try (
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("e:\\demo\\Kobe Bryant'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 end time
        long end = System.currentTimeMillis();
        System.out.println("Buffer stream copy time:"+(end - start)+" millisecond");
    }
}

Operation results:
Buffer stream copy time:3498 millisecond
 Normal stream replication time:319839 millisecond 
Copy code

After the program runs, you can deeply experience the speed of the buffer stream. The buffer stream has been copied successfully, but the ordinary stream has not been successful. Not only failed, but also took a long time. You can feel that the buffer stream is dozens of times that of an ordinary stream. My video is only 46.2M in size. What if it is a larger file, a few hundred megabytes or even a few gigabytes? Then I can't finish the transmission all day. Isn't this Baidu online disk?

Do you think it's not fast enough and want to experience the feeling of flying. Now I'll take you to the cloud top. Hey, hey, the old driver is going to drive. Don't get carsick.

Next, use the array method to experience:

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

    }

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

        try(
                FileInputStream fis = new FileInputStream("e:\\demo\\Kobe Bryant'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) + "millisecond");
    }

    public static void bufferedCopy() {
        //start time
        long start = System.currentTimeMillis();
        // Create flow object
        try (
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("e:\\demo\\Kobe Bryant'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 uses array copy time:"+(end - start)+" millisecond");
    }
}

Program execution results:
Buffer stream uses array copy time:370 millisecond
 Normal stream array copy time: 1016 MS
 Copy code

Is the speed faster? If it's not fast enough, you can change byte[] bytes = new byte[1024] to byte[] bytes = new byte[1024*8]. Can make you experience more efficient. You'll feel the speed flying into the sky.

Character buffer stream

1. Construction method

  • public BufferedReader(Reader in): create a new buffered input stream. The type of the passed in parameter is Reader.

  • public BufferedWriter(Writer out): create a new buffered output stream. The type of the incoming parameter is Writer.

    The demonstration is as follows:

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

2. Unique methods

It is not used for byte buffer stream and character ordinary stream. It has something that others do not have. What is it? Let's take a look at it now:

  • Character buffer input stream BufferedReader: public String readLine(): read a line of text. If it is read to the end, it will return NULL.

  • Character buffer output stream BufferedWriter: public void newLine(): write a line separator, that is, a new line, and the symbol is defined by the system attribute.

    Step by step to demonstrate the following:

    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 data
              bw.write("Hello");
              //Line feed
              //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, view hello.txt The information is:
      Hello
      world
      Java
      newLine
       Copy 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"));
      
              //Definition get string
              String line = null;
              while((line = br.readLine()) != null) {
                  System.out.println(line);
              }
              br.close();
          }
      }
      
      After the program is executed, view hello.txt The information is:
      Hello
      world
      Java
      newLine
       Copy code

Text sorting case

What is the text sorting exercise? Let me share my favorite song, and then arrange it in a certain order. Of course, don't worry. There must be a way for you to reorder.

8.Since the target is the horizon
7.I don't think whether there will be cold wind and rain behind me
3.Just take care of the wind and rain
9.What is left to the world is only the back
4.I don't want to win love
5.Since I love roses
6.Just confide your sincerity bravely
10.I don't think about whether the future is flat or muddy
11.Just love life
12.Everything is expected
5.Since I love roses
6.Just confide your sincerity bravely
1.I don't think about whether I can succeed
2.Now that you have chosen the distance
 Copy code

"Love life" comes from Wang Guozhen's poetry collection. To tell the truth, this composition I wrote in high school has always been quoted by me. Not only this one, but also Wang Guozhen's "thanks". A lt hough I haven't got a particularly high score for my composition so far, it can't hinder my love for Wang Guozhen's works. Just as I wanted to harvest a wisp of spring breeze, you gave me the whole summer. You have to believe that your talent will not be buried forever. So when we cross a mountain, we cross a real self.

Well, Stop, back to the point: how do we sort this poem.

analysis:

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

  • Then don't you have to parse the text? Shall we use the first two rows? But if I have more than one text, there are hundreds of lines, which is three digits. It is not advisable to display this method.

  • We should see that there is a character "." after the serial number, We can start with this defect. Then store the split sequence number and text in the set. For this CP combination, we can use the Map set.

  • Then write the ordered text back into the file.

  • OK, now that we know the idea, let's work together:

    public class BufferedTest6 {
        public static void main(String[] args) throws IOException {
            //Create character input stream object
            BufferedReader br = new BufferedReader(new FileReader("e:\\demo\\Love life.txt"));
    
            //Create character output stream object
            BufferedWriter bw = new BufferedWriter(new FileWriter("e:\\demoCopy\\Love life.txt"));
    
            //Create a Map collection to save future data. The key is sequence number and the value is text.
            HashMap<String, String> map = new HashMap<>();
    
            //Read data
            String line = null;
            while((line = br.readLine()) != null) {
                //Pass To split text and sequence numbers
                String[] split = line.split("\\.");
                //Store the obtained data into the set
                map.put(split[0], split[1]);
            }
    
            //Next, don't you get the text by pressing the serial number, that is, the key to find the value
            for (int i = 1; i <= map.size(); i++) {
                String key = String.valueOf(i);
                //Key value finding
                String value = map.get(key);
    
                //If I get the text, I still write the serial number here. I'm afraid you think I'm ignorant of you. If I believe my classmates, I don't have 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 resources
            bw.close();
            br.close();
        }
    }
    Copy code

    After the program runs, as expected, you can see from the file:

    1.I don't think about whether I can succeed
    2.Now that you have chosen the distance
    3.Just take care of the wind and rain
    4.I don't want to win love
    5.Since I love roses
    6.Just confide your sincerity bravely
    7.I don't think whether there will be cold wind and rain behind me
    8.Since the target is the horizon
    9.What is left to the world is only the back
    10.I don't think about whether the future is flat or muddy
    11.Just love life
    12.Everything is expected
     Copy code

    If you don't want to have a serial number, you can choose not to write the serial number.

summary

I believe all of you have a certain understanding of the buffer stream class in the advanced stream of IO stream, and look forward to waiting for the advanced stream - conversion stream teaching in the next chapter!

Of course, there are a lot of streams waiting to see together next time! Welcome to the next chapter!

Learn here, today's world is closed, good night! Although this article is over, I am still there and will never end. I will try to keep writing articles. The future is long. Why are you afraid of cars and horses!

Thank you for seeing here! May you live up to your youth and have no regrets!

Note: if there are any mistakes and suggestions in the article, please leave a message! If this article is also helpful to you, I hope you can pay attention to it. Thank you very much!


Author: Prince Nezha
Link: https://juejin.cn/post/6994718043582496805
Source: Nuggets
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.

Keywords: Java

Added by mikeschuld on Sun, 26 Dec 2021 17:41:53 +0200