BufferedReader在应该的时候没有说“准备好” [英] BufferedReader not stating 'ready' when it should

查看:104
本文介绍了BufferedReader在应该的时候没有说“准备好”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 BufferedReader 通过URL上的InputStreamReader(到某些Apache服务器上的文件)从Web文档中读取文本。

  String result =; 
URL url =新URL(http://someserver.domain/somefile);
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(url.openStream(),iso-8859-1));

结果+ = in.readLine();

现在这很好用。但显然我希望读者不要只阅读一行,而是阅读文件中的一行。

查看BufferedReader API,下面的代码就是这样:

  while(in.ready()){
result + = in.readLine();
}

I.e。当有更多行时读取所有行,当没有更多行时停止。但是这段代码不起作用 - 读者从不报告 ready()= true



我甚至可以在读取一行(从文件中读取正确的字符串)之前打印ready()值,但读者将报告' false '。



<我做错了什么?当实际有东西要读时,为什么BufferedReader会准备好' false '?

解决方案

ready()!=有更多



ready()并不表示存在是要读取的更多数据。它仅显示读取 是否可以阻止该线程。在您读取所有数据之前,它很可能会返回false。



要查看是否有更多数据,请检查 readLine()返回 null

  String line = in .readLine(); 
while(line!= null){
...
line = in.readLine();
}


I am trying to read text from a web document using a BufferedReader over an InputStreamReader on an URL (to the file on some Apache server).

String result = "";
URL url = new URL("http://someserver.domain/somefile");
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(url.openStream(), "iso-8859-1"));

result += in.readLine();

Now this works just fine. But Obviously I'd like the reader not to just read one line, but as many as there are in the file.
Looking at the BufferedReader API the following code should do just that:

while (in.ready()) {
    result += in.readLine();
}

I.e. read all lines while there are more lines, stop when no more lines are there. This code does not work however - the reader just never reports ready() = true!

I can even print the ready() value right before reading a line (which reads the correct string from the file) but the reader will report 'false'.

Am I doing something wrong? Why does the BufferedReader return 'false' on ready when there is actually stuff to read?

解决方案

ready() != has more

ready() does not indicate that there is more data to be read. It only shows if a read will could block the thread. It is likely that it will return false before you read all data.

To find out if there is no more data check if readLine() returns null.

String line = in.readLine();
while(line != null){
   ...
   line = in.readLine();
}

这篇关于BufferedReader在应该的时候没有说“准备好”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆