Java - Buffered input and output streams (BufferedInputStream, BufferedOutputStream)

    Buffer Buffer It is a part of the memory space. A certain storage space is reserved in the memory space. These storage spaces are used to buffer input or output data. This part of the space is called a buffer, and the buffer has a certain size.


    There is an imbalance between the speed of data transmission and the speed of data processing. For example, 50 hard disk writes per second have a great impact on the system, and a lot of time is wasted busy processing the two events of start writing and end writing, and temporarily store them in buffer , It becomes writing to the hard disk every 5 seconds, the data can be sent directly to the buffer, high-speed devices do not have to wait for low-speed devices, the impact on the system is small, and the writing efficiency is high.


    The following introduces the usage of the two advanced streams BufferedInputStream and BufferedOutputStream in reading and writing, taking copying files as an example.



insert image description here



FileInputStream fis = new FileInputStream(file directory)


// Encapsulate fis into BufferedInputStream object
BufferedInputStream bis = new BufferedInputStream(fis);



FileOutputStream fos = new FileOutputStream(file directory);


// Encapsulate fos into BufferedOutputStream object
BufferedOutputStream bos = new BufferedOutputStream(fos);


    Among them, bos.flush() can actually ignore this flush buffer stream. Just call bis.close() and bos.close().



    Visible through the underlying code of BufferedInputStream, Inputstream has been closed



insert image description here



    Then through the underlying code of BufferedOutputStream, although there is no close() method, according to the new feature of JDK7 try (declared here will be automatically closed), so OutputStream is also automatically closed, and then call the flush() method to execute.



insert image description here



    The core code is as follows:



public class Buffer_IO_Stream {
    
    

    public static void main(String[] args){
    
    
        try {
    
    
            FileInputStream fis = new FileInputStream("C:\\Users\\Administrator\\Desktop\\test\\1230.txt");
            BufferedInputStream bis  = new BufferedInputStream(fis);

            FileOutputStream fos  = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\test\\copy.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            int size;
            byte[] buf  = new byte[1024];
            while ((size=bis.read(buf))!=-1){
    
    
                bos.write(buf,0,size);
            }

            // bos.flush();
            bis.close();
            bos.close();
        }
        catch(Exception e){
    
    
        }
    }
}


Guess you like

Origin blog.csdn.net/weixin_48591974/article/details/128121327