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.


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.


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.

2 thoughts on “Java Scanner and Input Streams

  1. I would like to convey my admiration for your generosity in support of men and women that have the need for help with this particular concern. Your special dedication to getting the message all over had been wonderfully productive and have all the time made professionals much like me to attain their dreams. Your own invaluable tutorial means a great deal to me and additionally to my office workers. Thank you; from everyone of us.

Leave a Reply

Your email address will not be published. Required fields are marked *