Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

BufferedOutputStream and BufferedInputStream in Java IO are introduced in detail.

1 BufferedOutputStream Output stream of buffer bytes

public class BufferedOutputStream
extends FilterOutputStream
Copy the code

Features: Provides buffers that can be automatically expanded, improving write efficiency.

1.1 the constructor

public BufferedOutputStream(OutputStream out)
Copy the code

Create a new buffered output stream with the default buffer size (large enough) to write data to the specified underlying output stream. Out: indicates the underlying output stream.

1.2 API methods

All methods are inherited and overridden from the parent FilterOutputStream; no new methods are provided.

void write(int b);  // Write one byte at a time
void write(byte[] b);
void write(byte[] b, int off, int len);  // Write one part of the array \ one byte at a time
void flush(a);
void close(a);
Copy the code

2 BufferedInputStream Buffer byte input stream

public class BufferedInputStream
extends FilterInputStream
Copy the code

Features: Provides buffers that can be automatically expanded, improving read efficiency.

2.1 the constructor

public BufferedInputStream(InputStream in)
Copy the code

Create a buffered input stream and save its parameters, the input stream IN, to read data from IN. In: indicates the underlying input stream.

2.2 API methods

All methods inherit and override the parent FilterInputStream method, providing no new methods.

int read(a);  
int read(byte[] b); 
int read(byte[] b, int off, int len);
int available(a);   
void close(a);
Copy the code

3 cases

Use byte stream with buffer to achieve file copy.

/ * * *@author lx
 */
public class BufferedStreamCopy {

    public static void main(String[] args) throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("C:\\Users\\lx\\Desktop\\test.wmv"));
            bos = new BufferedOutputStream(new FileOutputStream("C:\\Users\\lx\\Desktop\\test2.wmv"));
            byte[] by = new byte[1024];
            int i;
            while((i = bis.read(by)) ! = -1) {
                bos.write(by, 0, i); bos.flush(); }}catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            if(bis ! =null) {
                bis.close();
            }
            if(bos ! =null) { bos.close(); }}}}Copy the code

If you need to communicate, or the article is wrong, please leave a message directly. In addition, I hope to like, collect, pay attention to, I will continue to update a variety of Java learning blog!