views:

99

answers:

5

[Input|Output]Streams exist since JDK1.0, while their character-counterparts Readers|Writers exist since JDK1.1.

Most concepts seem similar, with one exception: the base classes of streams declare an abstract method which processes one single byte at a time, while base readers/writers classes declare an abstract method which processes whole char-arrays.

Thus, given that I understand it correctly, every overridden stream class is limited to process single bytes (thereby performing at least one method call for each byte!), while overridden readers/writers only need a method call per array(-buffer).

Isn't that a huge performance problem?

Can a stream be implemented as subclass of either InputStream or OutputStream, but nevertheless be based on byte-arrays?

+5  A: 

Actually, subclasses of InputStream have to override the method that reads a single byte at a time, but also can override others methods that read while byte-arrays. I think that's actually the case for most of the Input/Output streams.

So this isn't much of a performance problem, in my opinion, and yes, you can extend Input/Output stream and be based on byte-arrays.

Vivien Barousse
+3  A: 

Single byte reading is almost always a huge performance problem. But if you read the API docs of InputStream, you see that you HAVE TO override read(), but SHOULD also override read(byte[],int,int). Most code that uses any kind of InputStream calls the array style method anyway, but the default implementation of that function is just implemented by calling read() for every byte, so the negative performance impact.

For OutputStream the same holds.

Daniel
+1  A: 

As Daniel said, you must override read(), since client might use it directly, but you also should override read (byte[],int,int).

However, I doubt if you should be concerned with performance since the jvm can and will inline that method for you. Most of all, it doesn't seem like an issue to me.

Also, most readers use some underlying input stream behind the scene, so in any case those char-array based methods end up calling read(byte[],int,int) or even read() directly.

Yoni
A: 

performance wise, if you wrap it with BufferedInputStream, JVM should be able to optimize the overhead of single byte read method calls to nothing, i.e. it's as fast as if you do the buffering yourself.

irreputable
+1  A: 

Note that Readers/Writers are for reading characters which can be made of more than one byte such as unicode characters. Streams on the other hand are more suitable when you're dealing with non-string (binary) data.

Apart from that, InputStream and OutputStream also have methods to read/write an entire array of bytes.

Andre Holzner
I know, I was talking about **abstract** methods. But now, you and other answerers made clear, that other methods are also suited to be overridden.
java.is.for.desktop