简体   繁体   中英

What's the difference between BufferedInputStream and java.nio.Buffer?

We can get a BufferedInputStream by decorating an FileInputStream . And Channel got from FileInputStream.getChannel can also read content into a Buffer .

So, What's the difference between BufferedInputStream and java.nio.Buffer ? ie, when should I use BufferedInputStream and when should I use java.nio.Buffer and java.nio.Channel ?

Getting started with new I/O (NIO) , an article excerpt:

A stream-oriented I/O system deals with data one byte at a time . An input stream produces one byte of data, and an output stream consumes one byte of data. It is very easy to create filters for streamed data . It is also relatively simply to chain several filters together so that each one does its part in what amounts to a single, sophisticated processing mechanism. On the flip side, stream-oriented I/O is often rather slow .

A block-oriented I/O system deals with data in blocks . Each operation produces or consumes a block of data in one step. Processing data by the block can be much faster than processing it by the (streamed) byte. But block-oriented I/O lacks some of the elegance and simplicity of stream-oriented I/O .

These classes where written at different times for different packages.

If you are working with classes in the java.io package use BufferedInputStream.

If you are using java.nio use the ByteBuffer.

If are not using either you could use a plain byte[]. ByteBuffer has some useful methods for working with primitives so you might use it for that.

It is unlikely there will be any confusion because in general you will only use one when you have to and in which case only one will compile when you do.

I think we use BufferedInputStream to wrap the InputStream to make it works like block-oriented. But when deal with too much data, it actually consume more time than the real block-oriented I/O ( Channel ), but still faster than the unwrapperd InputStream .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM