Java-Sockets: InputStream.read() vs BufferedReader

2019-07-04 12:01发布

问题:

I'm reading from a Socket's InputStream. Because I'm parsing the incoming data on the fly, I'm required to read character by character.

Does BufferedReader.read() the same thing as InputStream.read() does ? (assuming that BufferedReader has been constructed with the InputStream as base)

Is it more efficient to use InputStream.read() when reading each character separately? Or is there any better way?

回答1:

BufferedReader will read multiple characters from an underlying Reader. An InputStream is providing bytes. So they're working on 2 distinct datatypes. How are you wrapping a Reader around a Stream ? Presumably you've go something like:

 BufferedReader in
   = new BufferedReader(new InputStreamReader(socket));

in which case I'd be careful to specify your character encoding.

From the perspective of optimisation, it would be better to use the BufferedReader, since it'll read several kilobytes at once, and you can take each character when you want (not necessarily forcing a new IO read).



回答2:

read() method of InputStream class is an abstract method. It should be InputStreamrReader I guess. Comming back to your question, both read() method of InputStreamReader and BufferesReader class do the same thing- return the ascii value of a character, the only difference being BufferedReader uses what is called buffering that allows us to reduce the how often we read from the disk/STDIN by copying chunks to main memory where as using InputStreamReader each invocation of read() could cause bytes to be read from disk/STDIN, converted into characters, and then returned, which can be very inefficient.