Summary of Java IO Stream Learning III: Buffer Stream
For reprinting, please indicate the source: http://blog.csdn.net/zhaoyanjun6/article/details/54894451
This article is from [Zhao Yanjun's blog]
InputStream
|__FilterInputStream
|__BufferedInputStream
First of all, let's ask why Buffered InputStream is needed with InputStream.
Buffered InputStream and Buffered OutputStream are subclasses of FilterInputStream and FilterOutputStream respectively. They are used as decorator subclasses to prevent actual write operations every time data is read/sent, representing the use of buffers.
It is necessary to know that no buffer operation, every byte read to write a byte, because the IO operation involving disk is much slower than the operation of memory, so the flow efficiency without buffer is very low. Buffered streams can read many bytes at a time, but do not write to disk, just put them in memory first. When the size of the buffer is enough, write to the disk once. This way can reduce the number of disk operations, and the speed will be improved a lot! __________
At the same time, because they implement buffer function, we should pay attention to using BufferedOutputStream to write data, call the flush() method or close() method, and force the data in the buffer to write out. Otherwise, you might not be able to write data. Similarly, there are BufferedReader and BufferedWriter classes.
Now you can answer the questions raised at the beginning of this article:
BufferedInputStream and BufferedOutputStream classes are input/output streams that implement buffering. With buffered input and output streams, it is more efficient and faster.
Conclusion:
Buffered Input Stream is a buffer input stream. It inherits from FilterInputStream.
BufferedInputStream's role is to add some functionality to another input stream, such as providing "buffer functionality" and supporting mark() tags and reset() reset methods.
BufferedInputStream is essentially implemented through an internal buffer array. For example, after building a Buffered InputStream corresponding to an input stream, when we read the data of the input stream through read(), Buffered InputStream will fill the data of the input stream into the buffer in batches. Whenever the data in the buffer is read out, the input stream fills the data buffer again; this is repeated until we have read the data location of the input stream.
Introduction to the Buffered InputStream API
Source code keyword segment analysis
private static int defaultBufferSize = 8192;//The size of the built-in cache byte array is 8KB
protected volatile byte buf[]; //Built-in cache byte array
protected int count; //The total number of bytes in the current buf, note that it is not the total number of bytes in the source of the underlying byte input stream
protected int pos; //The next read byte subscript in the current buf
protected int markpos = -1; //The location of the next read byte in buf recorded by the last call to mark(int readLimit) method
protected int marklimit; //Maximum amount of data read from in by cloud search after marking and before subsequent reset() method failures, to limit the maximum buffer after marking
Constructor
BufferedInputStream(InputStream in) //Build bis with default buf size, underlying byte input stream
BufferedInputStream(InputStream in, int size) //Build bis using specified buf size, underlying byte input stream
Introduction of general methods
int available(); //Returns the number of bytes available for reading from the source corresponding to the underlying stream
void close(); //Close the stream and release all resources associated with it
boolean markSupport(); //Check if this stream supports mark
void mark(int readLimit); //Mark the subscript of the next byte read by the current buf
int read(); //Read the next byte in buf
int read(byte[] b, int off, int len); //Read the next byte in buf
void reset(); //Reset the position in the buf that last calls the mark tag
long skip(long n); //Skip n bytes, not only valid bytes in buf, but also bytes in the source of in
Brief introduction to Buffered Output Stream API
Key fields
protected byte[] buf; //Built-in cache byte array, bytes to be written to out by the stored program
protected int count; //Total number of bytes in the built-in cache byte array
Constructor
BufferedOutputStream(OutputStream out); //bos are constructed using default size, underlying byte output stream. The default buffer size is 8192 bytes (8KB)
BufferedOutputStream(OutputStream out, int size); //Constructing bos with specified size, underlying byte output stream
Constructor source code:
/**
* Creates a new buffered output stream to write data to the
* specified underlying output stream.
* @param out the underlying output stream.
*/
public BufferedOutputStream(OutputStream out) {
this(out, 8192);
}
/**
* Creates a new buffered output stream to write data to the
* specified underlying output stream with the specified buffer
* size.
*
* @param out the underlying output stream.
* @param size the buffer size.
* @exception IllegalArgumentException if size <= 0.
*/
public BufferedOutputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
General method
// To mention here, `BufferedOutputStream'does not have its own `close' method. When he calls the parent `FilterOutputStrem'method to close, he indirectly calls the `flush' method implemented by himself to flush the remaining bytes in buf into out and `out.flush()` into the destination, as does DataOutputStream. Void flush (); flush the data written to bos to the destination specified by out, note that this is not flush to out, because it calls out.flush() internally. write(byte b); write a byte to buf write(byte[] b, int off, int len); write part of B into buf
1.BufferedOutputStream automatically flush when close()
2.BufferedOutputStream calls flush only when it is discontented with the buffer and needs to write the contents of the buffer to a file or send it to another machine through the network without calling close().
Practice 1: Copy files.
Operation: Use the buffer stream to copy the image named 123.png into abc.png in the F disk root directory
package com.app;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class A3 {
public static void main(String[] args) throws IOException {
String filePath = "F:/123.png" ;
String filePath2 = "F:/abc.png" ;
File file = new File( filePath ) ;
File file2 = new File( filePath2 ) ;
copyFile( file , file2 );
}
/**
* Copy file
* @param oldFile
* @param newFile
*/
public static void copyFile( File oldFile , File newFile){
InputStream inputStream = null ;
BufferedInputStream bufferedInputStream = null ;
OutputStream outputStream = null ;
BufferedOutputStream bufferedOutputStream = null ;
try {
inputStream = new FileInputStream( oldFile ) ;
bufferedInputStream = new BufferedInputStream( inputStream ) ;
outputStream = new FileOutputStream( newFile ) ;
bufferedOutputStream = new BufferedOutputStream( outputStream ) ;
byte[] b=new byte[1024]; //Represents reading up to 1KB of content at a time
int length = 0 ; //Represents the number of bytes actually read
while( (length = bufferedInputStream.read( b ) )!= -1 ){
//length represents the number of bytes actually read
bufferedOutputStream.write(b, 0, length );
}
//The contents of the buffer are written to the file
bufferedOutputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
if( bufferedOutputStream != null ){
try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if( bufferedInputStream != null){
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if( inputStream != null ){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if ( outputStream != null ) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Design sketch:
Personal micro-signal: Zhaoyan jun125, welcome attention