May 07

Java Scanner and Input Streams

This just took me a stupid long time to figure out, so I’m leaving it here for future reference.

In Java, the easiest way to read lines is using Scanner.  For work, I had written a quick Linux-only serial port implementation, with which I then took ideas from that for use in my cross-platform JavaSerial library.  What I was doing before was simply using a scanner to look for text coming in on the serial port, and splitting it up based on the lines using the scanner.  This worked fine.

Then I used JavaSerial.  And the Scanner wouldn’t work.

AT ALL.

As it turns out, Scanner doesn’t like using the normal read() method found in InputStream.  It instead uses the read() method which takes in a byte[] array.

If this was documented anyplace in the Javadocs, that would be good.  But it’s not.

UPDATE: 

I’ve figured out what the problem was. According to the Javadocs for the read( byte[], off, len ) method, it will block until it reads the entire length requested, which is stupid.  My implementation reads until either the end is reached OR there is no more data available(using the available() method).  See my implementation here.