Java 套接字:InputStream.read() 与 BufferedReader.read()
我正在从套接字的输入流中读取数据。因为我正在动态解析传入的数据,所以我需要逐个字符地读取。
BufferedReader.read()
与 InputStream.read()
相同吗? (假设BufferedReader是以InputStream为基础构造的)
单独读取每个字符时使用InputStream.read()是否更有效?或者有什么更好的办法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
BufferedReader 将从底层 Reader 读取多个字符。输入流正在提供字节。所以他们正在研究两种不同的数据类型。您如何将 Reader 包裹在 Stream 周围?想必您已经做了类似的事情:
在这种情况下,我会小心指定您的字符编码。
从优化的角度来看,最好使用 BufferedReader,因为它一次可以读取几千字节,并且您可以在需要时读取每个字符(不一定强制执行新的 IO 读取)。
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:
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).
InputStream类的read()方法是一个抽象方法。我猜应该是InputStreamrReader。回到你的问题,InputStreamReader 和 BufferesReader 类的 read() 方法都做同样的事情——返回字符的 ascii 值,唯一的区别是 BufferedReader 使用所谓的缓冲,这允许我们减少读取的频率通过将块复制到主内存来读取磁盘/STDIN,而使用 InputStreamReader 每次调用 read() 可能会导致从磁盘/STDIN 读取字节,转换为字符,然后返回,这可能非常低效。
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.