如果没有更多行,InputStreamReader 应该结束
我有一个 InputStreamReader
(与 BufferedReader
组合)。
我想在循环中读取 Stream 的内容
while((line = MyStream.readLine()) != null) {
s.o.p(line);
String lastline;
}
,但这会创建一个没有结束的循环,所以我的整个程序等待循环结束..并等待...并等待。
目前,我有一个方法,您可以指定应该读取多少行。这工作得很好,但是非常不灵活。
我目前的方法
public void getStatus(int times) throws IOException {
for (int i = 0; i < times; i++) {
System.out.println(fromServer.readLine());
}
我希望此方法读取所有行并将最后一行保存在字符串中,而无需“times”参数。
I have an InputStreamReader
(which is combined with a BufferedReader
).
I want to read the content of the Stream in a loop
while((line = MyStream.readLine()) != null) {
s.o.p(line);
String lastline;
}
but this creates a loop without an end, so my whole program waits for the loop to end .. and waits ... and waits.
At the moment, I've got a method where you can say how many lines should be read. This works fine, but is very inflexible.
My method at the moment
public void getStatus(int times) throws IOException {
for (int i = 0; i < times; i++) {
System.out.println(fromServer.readLine());
}
I want this method to read all lines and save the last one in a string without the "times" parameter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您获得的代码到达流的末尾,它就会起作用。
我的猜测是这是一个网络流,而另一端没有关闭连接。但这不会导致您无限地进入循环 - 它最终会导致您只是挂在 readLine 调用上,等待另一端关闭流,或者等待更多数据即将到达。
您需要有某种方法来检测您是否已完成(例如终止行/连接关闭)或者知道要提前读取多少行。
The code you've got will work if it reaches the end of a stream.
My guess is that this is a network stream, and the other end isn't closing the connection. That won't end up with you going into the loop ad infinitum though - it'll end up with you just hanging on the
readLine
call, waiting for either the other end to close the stream, or for more data to arrive.You need to either have some way of detecting you're finished (e.g. a terminating line / the connection closing) or know how many lines to read ahead of time.