Java-Sockets: InputStream.read() vs BufferedReader.read()

人走茶凉 提交于 2019-12-23 11:59:13

问题


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.



来源:https://stackoverflow.com/questions/1550606/java-sockets-inputstream-read-vs-bufferedreader-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!