Java 套接字:InputStream.read() 与 BufferedReader.read()

发布于 2024-08-07 14:33:51 字数 229 浏览 5 评论 0原文

我正在从套接字的输入流中读取数据。因为我正在动态解析传入的数据,所以我需要逐个字符地读取。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷弦 2024-08-14 14:33:51

BufferedReader 将从底层 Reader 读取多个字符。输入流正在提供字节。所以他们正在研究两种不同的数据类型。您如何将 Reader 包裹在 Stream 周围?想必您已经做了类似的事情:

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

在这种情况下,我会小心指定您的字符编码。

从优化的角度来看,最好使用 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:

 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).

看轻我的陪伴 2024-08-14 14:33:51

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文