使用 BufferedReader.readLine() 读取 inputStream 太慢
我正在使用以下代码。
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuilder responseData = new StringBuilder();
while((line = in.readLine()) != null) {
responseData.append(line);
}
但读取200行需要12秒以上。
请帮忙
I am using following code.
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
StringBuilder responseData = new StringBuilder();
while((line = in.readLine()) != null) {
responseData.append(line);
}
But it is taking more than 12 sec to read 200 line.
Please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我强烈怀疑这是因为网络连接或您正在交谈的 Web 服务器 - 这不是
BufferedReader
的错。尝试测量一下:我想您会发现它与解析文本的时间几乎完全相同。
请注意,您还应该为
InputStreamReader
提供适当的编码 - 平台默认编码几乎肯定不是您应该使用的编码。I strongly suspect that's because of the network connection or the web server you're talking to - it's not
BufferedReader
's fault. Try measuring this:I think you'll find it's almost exactly the same time as when you're parsing the text.
Note that you should also give
InputStreamReader
an appropriate encoding - the platform default encoding is almost certainly not what you should be using.我有一个更长的测试要尝试。将其添加到列表中时,读取每一行平均需要 160 ns(这可能是您想要的,因为删除换行符不是很有用。
prints
如果您想构建 StringBuilder,保留换行符,我建议 在这两种情况
都受到发送方而非接收方的限制。通过优化发送方,我将每行时间降低到 105 ns。
下,速度
I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.
prints
If you want to build a StringBuilder, keeping newlines I would suggets the following approach.
Still prints
In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.