Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a class that exposes an unbuffered readLine method in Java?

I'm cleaning up some chunks of our codebase at work, and one of the older classes is used to read and write data. This data is a mixture of US-ASCII encoded Strings and binary encoded primitives.

The current implementation uses DataInputStream, but as you can see in the documentation the readLine() method is deprecated because of an issue related to converting bytes to characters. While this encoding issue hasn't really popped up for us, the deprecation is an issue since it already doesn't work on some version of OpenJDK 7 and deprecation means that it could be removed entirely in the future. The "official" alternative is to use readLine from BufferedReader, but we can't do a complete swap-out with DataInputStream since BufferedReader can't really handle the binary encoded primitives.

The problem with "mixing" these two classes is that when the BufferedReader buffers off the stream, it advances the stream marker. This means that subsequent calls to methods like readDouble() from DataInputStream will fail with IOExceptions or EOFExceptions since the real location of the stream marker isn't where it "should" be in the context of the application logic.

I looked in to some sort of hacky mark()/reset() strategy but sometimes the stream is backed by a FileInputStream, which doesn't support mark()/reset().

Outside of changing our data protocol to write out the primitives as characters or writing my own implementation of readLine() (which is surprisingly non-trivial), is there any way to achieve this? I'd even be willing to consider an external library at this point.

like image 756
Doug Stephen Avatar asked Jul 04 '12 15:07

Doug Stephen


1 Answers

If the current codebase works well and if your only issue is the deprecation tag, I'd personally recommend copying the code from the readLine method of the DataInputStream class and moving it to a helper/utility class. The readLine method of the DataInputStream doesn't use a lot of instance variables so with a bit of work you should be able to work with it fine. A sample invocation will look like: Utils.readLine(dataInStream). This will ensure that even if the method is removed, your codebase isn't affected.

Yes, it's hacky and yes it looks a bit ugly but is the quickest and probably the safest alternative (minimal changes to the remaining code base).

like image 158
Sanjay T. Sharma Avatar answered Oct 03 '22 00:10

Sanjay T. Sharma