Buffered input streams read more data than they initially need into a buffer (an internal array of bytes). When one of the stream’s read() methods is invoked,data is removed from the buffer rather than from the underlying stream. When the buffer runs out of data,the buffered stream refills its buffer from the underlying stream. Also,buffered output streams store data in an internal byte array until the buffer is full or the stream is flushed. Then the data is written out to the underlying output stream in one swoop. In situations where it’s almost as fast to read or write several hundred bytes from the underlying stream as it is to read or write a single byte,a buffered stream can provide a significant performance boost.
I am going to show example which uses BufferedInputStream and BuffereOutputStream:
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class Main{ public static void main(String[] args){ try{ copyText(System.in,System.out); } catch (IOException ex){ System.err.println(ex); } } public static void copyText(InputStream inputStream,OutputStream outputStream) throws IOException{ BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); while (true){ int data = bufferedInputStream.read(); if (data == -1){break; } bufferedOutputStream.write(data); } bufferedOutputStream.flush(); }}
Download code from this post.
No related posts.

Recent Comments