问题描述
我从一个url中的文本文件中获取一行作为字符串,然后该字符串返回正确的值。但是,如果我在读取后调用字符串,则字符串返回null。
I grab a line from a text file from a url as a string, and the string returns the correct value. However, if i call the string after the read the string returns null.
我不知道发生了什么,并希望得到任何指导。
I have no idea what's going on and would appreciate any guidance.
static protected String readURL() {
String u = "http://adamblanchard.co.uk/push.txt";
URL url;
InputStream is;
InputStreamReader isr;
BufferedReader r;
try {
System.out.println("Reading URL: " + u);
url = new URL(u);
is = url.openStream();
isr = new InputStreamReader(is);
r = new BufferedReader(isr);
do {
str = r.readLine();
if (str != null)
System.out.println(str); //returns correct string
} while (str != null);
} catch (MalformedURLException e) {
System.out.println("Invalid URL");
} catch (IOException e) {
System.out.println("Can not connect");
}
System.out.println(str); //str returns "null"
return str;
}
推荐答案
BufferedReader.readLine()
方法在到达文件末尾时返回 null
。
The BufferedReader.readLine()
method returns null
when it reaches the end of file.
您的程序似乎正在读取并打印文件中的每一行,最后在底部打印 str
的值。鉴于终止读循环的条件是 str
是 null
,那么(相当不出所料)是打印的内容,以及该方法返回的内容。
Your program appears to be reading and printing each line in the file, and finally printing the value of str
at the bottom. Given that the condition for terminating the read loop is that str
is null
, that (rather unsurprisingly) is what is printed, and what is returned by the method.
这篇关于字符串在bufferedreader之后返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!