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? i.e., 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.
Related
I'm new to I/O in Java, and read in one of the posts on this site that:
All streams behave in the same manner, even if the actual physical devices to which they are linked differ. Thus, the same I/O classes and methods can be applied to any type of device
Quoted from: Stream definition
What I can't wrap my head around is how is it that all streams (take the different byte stream subtypes for example - BufferedInputStream, FilterInputStream, ObjectInputStream, .., etc.) behave in the same manner and can be connected to any physical device, when they are implemented as different classes to supposedly offer varying functionality and accomodate different sources/destinations? For example, can I use ObjectInputStream or FileOutputStream to read from and write to the console? Different streams, different devices, and all (streams) can be connected to all (devices) - I'm at loss here..
The quote does not say that you can connect any stream to any device, as you are saying. There are different implementations of InputStream and OutputStream that connect to specific devices - for example, FileInputStream connects to a file on the filesystem, and ByteArrayInputStream connects to a byte array in memory.
The main idea that the quote is explaining is that all those different kinds of streams are all extensions of the classes InputStream and OutputStream, so that you can do all the common operations on streams using any of the specific kinds of streams, regardless of where the specific kind of stream reads or writes data from or to.
Some streams are wrappers around other streams, adding specific functionality. For example, BufferedOutputStream adds buffering to an underlying stream. This is often useful because for some streams, writing in blocks is more efficient than writing byte by byte - BufferedOutputStream collects bytes that you write into a buffer, which is then written to the underlying stream as one block. ObjectOutputStream is another wrapper, which adds the functionality to convert serializable Java objects to bytes which can be written to an underlying stream.
You cannot use every Stream for every device. According to the definition in your question (bold by me),
All streams behave in the same manner.
So you can use every Stream the same, which means every Stream has the same methods since they inherit from java.io.OutputStream or java.io.InputStream.
So it does not matter whether you want to write to the console or a file or a networt socket, you can e.g. always write a byte array to the device.
Nonetheless, there are different implementations which handle writing this byte array differently.
I'm looking for a good explaination of the difference between the "new" Streams in Java 8 and the "old" I/O Streams we had before in Java 7. For someone without any knowledge of functional programming, it's hard to get that those are complete different things, especially because the names are the same. I get that the Stream API is something completely new and even revolutionary in some point, but in my naive thinking, in both cases we deal with sequences of "things", be it bytes, data or objects...
Can someone please offer a good explaination?
It has nothing to do with each other and I agree, it's bad luck that IO Streams had their name before the "new" Streams have arrived. The I/O streams were meant as connections to external resources, mostly files, but also others. The new Streams are for functional programming and should be treated separately.
But you can actually use both concepts together. For example, a BufferedReader has a lines-method, which returns lines of a file (or other resources) as a Stream of Strings.
Let's take a look at the picture illustrated I/O stream.
There are three concerning concepts related to I/O stream: Source, Destination, and Element (represented by the letter 'e'), where
Source or Destination could by a file, network connection, pipe, memory buffer etc.
An Element is just simply a piece of data and a stream consist of a chunk of elements
When to use what?
I/O streams are for reading content from a source, or writing the content to a destination. That's it, simple :-)
The new Stream concept introduced in Java 8 has nothing to do with I/O streams. Streams are not themselves data structures, but Classes that allow you to manipulate a collection of data in a declarative way (functional-style operation).
In term of 'stream' there is no difference. Stream is abstract phrase that means something that has a source and destination. What is more it is something that represents sequence of data.
In term of these two mechanism there is a lot of differences. For example Java i/o streams let you only read and write data. If you want to process data from that stream there is no builded in mechanism for that. In Java 8 stream there are additional possibilities of processig like map/filter etc.
I am getting a hard time visualizing what exactly stream means in terms of IO. I imagine stream as a continuous flow of data coming from a file, socket or any other data source. Is that correct? But then I get confused on how our java programs react to stream because when we write any java code let say:
Customer getCustomer(Customer customer)
Doesn't the above java code expects the whole object to be present before it gets processed?
Now lets say we are reading from a stream something like
FileInputStream in = new FileInputStream("abc.txt")
in.read();
Doesn't in.read() expects the whole file to be present in memory to be processed. If it is, then how come it is a stream? Why do we call them streams? Do they process data as it is read?
A similar confusion when reading through hadoop streams, looks like they have a different meaning altogether.
The word "stream" is used for different things in different contexts. But you're specifically asking about streams in I/O, i.e. InputStream and OutputStream.
I imagine stream as a continuous flow of data coming from a file, socket or any other data source. Is that correct?
Yes, a stream is a source of a sequence of bytes, which may come from a file, socket etc.
About getCustomer: You need to have a Customer object to pass to that method. But calling methods, passing objects and getting objects returned really does not have anything to do with streams.
Doesn't in.read() expects the whole file to be present in memory to be processed.
No. FileInputStream is an object which represents the stream. It's the thing that knows how to read bytes from the file.
Streams are not a fundamentally special kind of object. It's not like that there are classes, objects and streams. Streams are just a concept that is implemented using the standard Java OO programming features (classes and objects).
Doesn't the above java code expects the whole object to be present before it gets processed?
Yes. But it's not a stream.
Doesn't in.read() expects the whole file to be present in memory to be processed.
No.
If it is
It isn't.
then how come it is a stream?
It is.
Why do we call them streams? Do they process data as it is read?
Yes.
A similar confusion
There is no confusion here, except your own confusion when comparing method calls with I/O streams, which comparing apples versus oranges.
when reading through hadoop streams, looks like they have a different meaning altogether.
Very possibly.
An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.
Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.
No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data.
In Java there are two kinds of streams (Byte & Character), they differ in the way how the data is transferred between source & destination.
Hope this answers your question. Please let me know if you need any further information.
From here..
A Stream is a free flowing sequence of elements. They do not hold any storage as that responsibility lies with collections such as arrays, lists and sets. Every stream starts with a source of data, sets up a pipeline, processes the elements through a pipeline and finishes with a terminal operation. They allow us to parallelize the load that comes with heavy operations without having to write any parallel code. A new package java.util.stream was introduced in Java 8 to deal with this feature.
Streams adhere to a common Pipes and Filters software pattern. A pipeline is created with data events flowing through, with various intermediate operations being applied on individual events as they move through the pipeline. The stream is said to be terminated when the pipeline is disrupted with a terminal operation. Please keep in mind that a stream is expected to be immutable — any attempts to modify the collection during the pipeline will raise a ConcurrentModifiedException exception.
I want to constantly write data to disc.
And I want to flush data to disc frequently (for example every chunk of 64MB). What solution can you propose?
I think standard OutputStream might be a better choice than nio.channels because it is more straightforward.
If you are writing a continuous stream of data, for example appending to the end of a file, regular OutputStream with flush() called once in a while is just as good or better than nio. Where nio could give you a big advantage would be writing many small chunks spread over different regions of a file. In that case you could use a memory mapped file and this could be an improvement over old-style writes. However, from the question I understand you are rather dealing with a continuous stream of data. I suggest you implement the regular solution which gives you code you find nicer and only search for alternatives if you find performance lacking. In this case I wouldn't expect nio to make noticeable difference.
Whenever I use HttpConnection Class in Java ME, Android or in BlackBerry, I uses DataInputStream/DataOutputStream class for reading & writing datas over remote server. However there are other class like InputStream/OutputStream which can be use for same purpose. I saw Question regarding InputStream/OutputStream class with HttpConnection. So I would like to know from experts that what are the differences between these two ?
DataInputStream/DataOutputStream is an InputStream/Outputstream. InputStream and OutputStream are the most generic IO streams you can use and they are the base class of all streams in Java. You can read and write raw bytes only with them. DataInputStream writes formatted binary data. Instead of just simple unformatted bytes, you can read Bytes, Integer, Double, Float, Short, UTF-8 strings, and any mixture of that data. And the same can be said for DataOutputStream except that it writes these higher level data types.
A DataInputStream/DataOutputStream has a reference to an InputStream/OutputStream which it reads the raw bytes and interprets those bytes as those previously mentioned data types.
Although reading strings from the DataInputStream isn't a good idea because it makes unchangeable assumptions about the character encoding of the underlying InputStream. Instead, it's better to use a Reader which will properly apply character encodings to the underlying byte stream to read data. That's why DataInputStream/DataOutputStream is of limited use. Typically it's better to trade textual data between processes because it's easiest to make a server and client agree on how to parse the data. Trading binary has lots of bit twiddling that has to occur to make sure each process is talking the same language. It's easy if you have two Java processes using DataInputStream/DataOutputStream, but if you ever want to add a new client that isn't Java you'll have a harder time reusing it. Not impossible, but just harder.
DataOutputStream can only handle basic types.
It can only read/write primtive types and Strings.DataInput/OutputStream performs generally better because its much simpler.
ObjectInput/OutputStream can read/write any object type was well as primitives. It is less efficient but much easier to use if you want to send complex data.
With the ObjectOutputStream class, instances of a class that implements Serializable can be written to the output stream, and can be read back with ObjectInputStream.
I would assume that the Object*Stream is the best choice until you know that its performance is an issue.
DataOutputStream makes sure the data is formatted in a platform independent way
OutputStream only if you transfer raw binary data.
DataOutputStream-This is the big benefit.
There is no significant performance difference between both.