如果没有更多行,InputStreamReader 应该结束

发布于 2024-11-19 20:30:53 字数 557 浏览 1 评论 0原文

我有一个 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 技术交流群。

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

发布评论

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

评论(1

无悔心 2024-11-26 20:30:53

如果您获得的代码到达流的末尾,它就会起作用。

我的猜测是这是一个网络流,而另一端没有关闭连接。但这不会导致您无限地进入循环 - 它最终会导致您只是挂在 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.

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