This is the 13th day of my participation in Gwen Challenge

Accumulate over a long period, constant dripping wears away a stone 😄

An overview,

Buffered streams, also known as efficient streams, are enhancements to the four basic FileXxx streams, so also four streams, classified by data type:

  • Byte buffer streams: BufferedInputStream, BufferedOutputStream
  • Character buffer streams: BufferedReader, BufferedWriter

The basic principle of buffer flow is that a built-in buffer array of default size is created when a stream object is created to reduce I/O times and improve read/write efficiency.

Byte buffer stream

1. BufferedOutputStream

BufferedOutputStream extends FilterOutputStream.

FilterOutputStream extends the OutputStream.

Member methods inherited from the parent class:

  • Void close() : Closes this output stream and frees any system resources associated with this stream.
  • Void flush() : Flushes this output stream and forces any buffered output bytes to be written out.
  • Void write(byte[] b) : writes b.length bytes from the specified byte array to this output stream.
  • Void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array, starting from offset OFF to the output stream.
  • Abstract void write(int b) : Writes the specified byte to the output stream.

A constructor

  • BufferedOutputStream(OutputStream out)

Creates a new buffered output stream to write data to the specified underlying output stream.

  • BufferedOutputStream(OutputStream out, int size)

Creates a new buffered output stream to write data to the specified underlying output stream at the specified buffer size

parameter

  • OutputStream out: byte OutputStream
  • Int size: Specifies the size of the internal buffer. The default value is 8192

For example, the code is as follows:

// Create file byte output stream
 FileOutputStream os = new FileOutputStream("IO stream / / e. xt");
// Create a byte buffered output stream
BufferedOutputStream bos= new BufferedOutputStream(os);
BufferedOutputStream bos2= new BufferedOutputStream(os,5);
Copy the code

Write the data

public static void main(String[] args) throws Exception {
    // Create a FileOutputStream object with the constructor bound to the output destination
    FileOutputStream os = new FileOutputStream("IO stream / / e. xt");
    // Create a BufferedOutputStream object, pass FileOutputStream in the constructor,
    // Improve FileOutputStream object efficiency
    BufferedOutputStream bos = new BufferedOutputStream(os);
    // Write data to the internal buffer using the BufferedOutputStream method write method
    bos.write("Test byte buffer output stream".getBytes());
    // Flush the data in the internal buffer to the file
    bos.flush();
    // Whether the resource is available (the data in the memory buffer is flushed to the file first)
    bos.close();
}
Copy the code

2. BufferedInputStream [byte buffer input stream]

BufferedInputStream extends FilterInputStream.

FilterInputStream extends InputStream.

Member methods inherited from the parent class:

  • Void close() : Closes this input stream and frees any system resources associated with the stream.
  • Abstract int read() : Reads the next byte of data from the input stream.
  • Int read(byte[] b) : Reads some bytes from the input stream and stores them in buffer B.
  • Int read(byte[] b, int off, int len) : Reads up to len bytes of data from the input stream into a byte array.

A constructor

  • BufferedInputStream(InputStream in)

Create a BufferedInputStream and save its parameters, entering the stream in for later use.

  • BufferedInputStream(InputStream in, int size)

Create BufferedInputStream with the specified buffer size and save its parameters, entering the stream in for later use.

parameter

  • InputStream in: byte InputStream
  • Int size: Specifies the size of the internal buffer. The default value is 8192

For example, the code is as follows:

// Create file byte input stream
  FileInputStream fs = new FileInputStream("IO stream \ \ e. xt." ");
// Create a byte buffered input stream
  BufferedInputStream bis = new BufferedInputStream(fs);
  BufferedInputStream bis2 = new BufferedInputStream(fs,5);
Copy the code

Read the data

// Create a FileInputStream object that binds the data source to be read
    FileInputStream fs = new FileInputStream("IO stream \ \ e. xt." ");
    // Create BufferedInputStream, pass FileInputStream in constructor,
    // Improve the efficiency of reading FileInputStream objects
    BufferedInputStream bis = new BufferedInputStream(fs);
    // Store data for each read
    byte[] bytes = new byte[102];
    int len = 0; // Record the number of valid bytes read each time
    // Read the file using the BufferedInputStream method read
    while((len = bis.read(bytes)) ! = -1){
        System.out.println(new String(bytes,0,len));
    }
    bis.close();
    fs.close();
Copy the code

The efficiency test

The buffer stream read-write method is consistent with the base stream, and we tested its efficiency by copying a large file (79.2 MB).

The basic flow

 public static void main(String[] args) throws Exception{
        long startTime = System.currentTimeMillis();
        // Create a FileInputStream object
        FileInputStream fis = new FileInputStream("D:\\dev\\1.jpg");
        // Create a FileOutputStream object
        FileOutputStream fos = new FileOutputStream("D:\\dev\\2.jpg");
        // Read multiple bytes at a time
        byte[] bytes = new byte[1024];
        int len = 0;
        while((len = fis.read(bytes)) ! = -1) {// Write the read stream to a file at the destination using the method write()
            fos.write(bytes,0,len);
        }
        // Free resources, close the written (if finished, must be finished)
        fos.close();
        fis.close();
        long endTime = System.currentTimeMillis();
        System.out.println("Total file replication time:" + (endTime - startTime) + "毫秒"); } Command output: Total file replication time:2103msCopy the code

Buffer flow

public static void main(String[] args) throws Exception {
    long startTime = System.currentTimeMillis();
    // Create a stream object
    try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\ Installation pack \\ Securecrt72.zip"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\ installation pack \\ Securecrt744442.zip")); {// Read and write data
        int len = 0;
        byte[] b = new byte[1024];
        while((len = bis.read(b)) ! = -1){
            bos.write(b,0,len); }}catch (IOException e){
        e.printStackTrace();
    }

    long endTime = System.currentTimeMillis();
    System.out.println(Buffer stream replication time:+(endTime - startTime)+"Ms"); } Buffer stream replication time:378msCopy the code

3, BufferedWriter [character buffer output stream]

BufferedWriter extends Writer.

Member methods inherited from the parent class:

  • Abstract void close() : Close the stream, but flush it first.
  • Abstract void flush() : Flushes the stream.
  • Void write(int C) : Writes a character
  • Void write(char[] cbuf) : Writes an array of characters.
  • Void write(char[] cbuf, int off, int len) : Writes part of the character array.
  • Void write(String STR) : Writes a String
  • Void write(String s, int off, int len) : Write part of a String.

Unique member methods:

  • Void newLine: Writes a line of delimiters. Gets different line separators depending on the operating system.win:\r\n linux:\n mac:\r

A constructor

  • BufferedWriter(Writer out)

Creates a buffered character output stream that uses the default size of the output buffer.

  • BufferedWriter(Writer out, int sz)

Creates a new buffered character output stream with the output buffer of the given size.

parameter

  • Writer out: character output stream

  • Int sz: Specifies the size of the buffer inside the buffer. Default: 8192

For example, the code is as follows:

// Create the FileWriter file character output stream object
 FileWriter fw = new FileWriter(\ \ "IO flow f.t xt." ");
// Create a character cache output stream object
 BufferedWriter bw = new BufferedWriter(fw);
 BufferedWriter bw2 = new BufferedWriter(fw,6);
Copy the code

Write the data

  public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter(\ \ "IO flow f.t xt." ");
        BufferedWriter bw = new BufferedWriter(fw);
        for (int i = 0; i < 10; i++) {
            bw.write("You're great.");
            / / a newlinebw.newLine(); } bw.flush(); bw.close(); } Output: You're great, you're great, you're great, you're great, you're great, you're great, you're great, you're great, you're great, you're greatCopy the code

4, BufferedReader [character buffer input stream]

BufferedReader extends the Reader.

Member methods inherited from the parent class:

  • Void close() : Closes the stream and frees any system resources associated with it.
  • Int read() : Reads a character
  • Int read(char[] cbuf, int off, int len) : Reads characters into part of an array.

Unique member methods:

String readLine: Reads a line of text. A line is treated as terminated by either a newline (‘\ n’), carriage return (‘\ r’) or a subsequent newline.

Return value: A string containing the contents of the row, excluding any line terminating characters, or null if the end of the stream has been reached

A constructor

  • BufferedReader(Reader in)

Creates a buffered character input stream that uses the default size of the input buffer.

  • BufferedReader(Reader in, int sz)

Creates a buffered character input stream that uses an input buffer of the specified size.

parameter

  • Reader in: character input stream
  • Int sz: Specifies the size of the buffer inside the buffer. Default: 8192

For example, the code is as follows:

// Create a file character input stream
  FileReader fr = new FileReader(\ \ "IO flow f.t xt." ");
 // Create a character buffered input stream
  BufferedReader br = new BufferedReader(fr);
  BufferedReader br2 = new BufferedReader(fr,5);
Copy the code

Read the data

Use the readLine method to read

public static void main(String[] args) throws Exception {
    //// Create a stream object
    FileReader fr = new FileReader(\ \ "IO flow f.t xt." ");
    BufferedReader br = new BufferedReader(fr);
  // Define a string that holds a line of text read
    String line = null;
 // Loop reads, returns null at the end
    while((line = br.readLine()) ! =null){
        System.out.println(line);
    }
  // Release resources
  br.close();
}
Copy the code
  • If you have any questions or errors in this article, please feel free to comment. If you find this article helpful, please like it and follow it.