Friday, May 8, 2009

Quick notes to self on java.io

Just a quick post so that I don't forget next time:

java.io.FilterOutputStream

If you extend java.io.FilterOutputStream, don't forget to override write(byte b[], int off, int len), since the default implementation falls back on looping write(byte b) which is terribly slow.
Also, when you also override write(byte[] b), make sure to call write(b,0,b.length); and not the super method:


@Override
public void write(byte[] b) throws IOException {
write(b,0,b.length);
}


Readers, Writers, Streams, that delegate to underlying source.
Always check if the implementation of the close() method, closes the underlying source automatically. Don't assume that it always will.
XMLStreamReader for instance, doesn't close the underlying source. FilterOutputStream does. BufferedWriter does. BufferedReader does. GZIPInputStream does.
(In my opinion this should be consistent, but it is not.)