Maximum line length for BufferedReader.readLine() in Java?

daphshez picture daphshez · May 11, 2011 · Viewed 33.2k times · Source

I use BufferedReader's readLine() method to read lines of text from a socket.

There is no obvious way to limit the length of the line read.

I am worried that the source of the data can (maliciously or by mistake) write a lot of data without any line feed character, and this will cause BufferedReader to allocate an unbounded amount of memory.

Is there a way to avoid that? Or do I have to implement a bounded version of readLine() myself?

Answer

Stephen C picture Stephen C · May 11, 2011

The simplest way to do this will be to implement your own bounded line reader.

Or even simpler, reuse the code from this BoundedBufferedReader class.

Actually, coding a readLine() that works the same as the standard method is not trivial. Dealing with the 3 kinds of line terminator CORRECTLY requires some pretty careful coding. It is interesting to compare the different approaches of the above link with the Sun version and Apache Harmony version of BufferedReader.

Note: I'm not entirely convinced that either the bounded version or the Apache version is 100% correct. The bounded version assumes that the underlying stream supports mark and reset, which is certainly not always true. The Apache version appears to read-ahead one character if it sees a CR as the last character in the buffer. This would break on MacOS when reading input typed by the user. The Sun version handles this by setting a flag to cause the possible LF after the CR to be skipped on the next read... operation; i.e. no spurious read-ahead.