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.
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.
So if there is a java.io.StringBufferInputStream, you would think that there would be a StringBufferOutputStream.
Any ideas as to why there isn't??
Likewise,there is also a SequenceInputStream but no SequenceOutputStream.
My guess is that someone never got around to making a StringBufferOutputStream in Java 1.0 since the product was somewhat "rushed to market." By the time Java 1.1 rolled around and people actually understood that readers and writers were for characters, and inputstreams and outputstreams were for bytes, the whole concept of using streams for strings was realized to be wrong, so the StringBufferInputStream was rightly deprecated, with no chance ever of a partner coming along.
A SequenceInputStream is a nice way to read from a bunch of streams all concatenated together, but it doesn't make much sense to write a single stream to multiple streams. Well, I suppose you could make sense of this if you wanted to write a large stream into multiple partitions (reminds me of Hadoop here). It's just not common enough to be in a standard library. A complication here would be that you would need to specify the size of each output partition and would really only make sense for files (which can have names with increasing suffixes, perhaps), and so would not generalize into arbitrary output streams in a nice manner.
StringBufferInputStream is deprecated, because bytes and characters are not the same thing. The correct classes to use for this are StringReader and StringWriter.
If you think about it, there is no way to make a SequenceOutputStream work. SequenceInputStream reads from the first stream until it is exhausted, then reads from the next stream. Since an OutputStream is never exhausted (unless, say, it happens to be connected to a socket whose peer closes the connection), how would a SequenceOutputStream class know when to move on to the next stream?
StringBufferInputStream has long been depreciated.
Use StringReader and StringWriter.
I am doing a project in which there are so many files I have to handle. Problem came when I have to provide file in different manner like:
File will contain one string in each line
numbers of char in each line e.g. :
1st line : A B 4
2nd line : 6 C A 6 & U #
etc.
File will contain no. of Strings e.g.
1st line : Lion Panther jaguar etc.
I have read how to efficiently handle file but I am so confused when to use Buffered Streams and when Unbuffered. If I am using BufferedStream then BufferInputStream and BufferReader / BufferWriter which should be used.
Similarly I am confuse with I/O Stream, File I/O Stream, ByteArray I/O Stream. There are so many things. Can any one suggest me when to use which one and why? What could be efficient handling according to the different scenarios?
Well, there might not be a direct answer for this, but you don't have to worry if you feel confused. Discussions about Buffered and Unbufferred have been done many times before.
For example in this link: bufferred vs non-bufferred, gives a good hint (check the answer marked as correct). This comes because while using Bufferred streams, those streams are stored in a small area of memory called (suprisingly) buffer. Same happens to written data (they go into the buffer before being stored into the hard memory). This improves performance because lowers the overhead of I/O operations (which are OS dependent). Check the Java Doc: Bufferred Streams
So, to make it clear, use Bufferred streams when you need to improve the performance of your I/O operations. Use Unbufferred streams when you want to ensure that the output has been written before continuing (because an error might always occur while writing from/into the buffer, an example might be when you want to write a log, it might be opened all the time, so there is no need to access it, no need for a buffer ).
Suppose I'm using a Deflater to compress a stream of bytes, and at some intervals I have the option of feeding it with two different byte arrays (two alternative representations of the same info), so that I can choose the most compressible one. Ideally, I would like to be able to clone the state of a "live" deflater, so that I can feed each instance with an array, check the results, and discard the undesirable one.
Alternatively, I'd like to mark the current state (sort of a savepoint) so that, after feeding and compressing with setInput() + deflate() I can rollback/reset to that state to try with different data.
Looking at the API, this seems to me rather impossible... nor even reimplementing the Deflater (not at least if one wants to take advantage of the internal native implementation). Am I right? Any ideas or experiences?
It does not appear that the Java interface to zlib provides zlib's deflateCopy() operation. It is possible that the inherited clone operation is properly implemented and does a deflateCopy(), but I don't know.