开发者

InputStreamReader should end if there are no more lines

I have an InputStreamReader (which is combined with a BufferedReader).

I wa开发者_JAVA百科nt 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜