Tuesday, 3 April 2007

Java Readers and Streams rant.

Another bit of Java design genius is the Reader/Stream architecture. Streams are low level things dealing with streams of bytes. Readers are higher level, and make working with character arrays easier. There is a useful class called InputStreamReader which takes a Stream, and converts it into a Reader so that you can work with the data as a stream of characters. All very nice, but also all very unidirectional...

Consider this: you have an object which loads data in via a load(InputStream is) method. The data you want to load is in a String you have obtained from elsewhere. OK, so what are your options? Is there a StringInputStream? no - but there is a StringBufferInputStream which looks spot on. Wait a minute - StringBufferInputStream is deprecated - apparently it doesn't properly convert characters to bytes. So rather than fix the implementation they say 'well actually, this class is rubbish - use StringReader instead'.

But I don't want a Reader, I want a Stream! So I have to write a wrapper class, which exposes the Readers read() method to the read() method of the new ReaderInputStream class. So, what would have been so hard about providing a ReaderInputStream to allow the backward conversion in the standard library?

No comments: