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;
}
The
BufferedReader.readLine()method returnsnullwhen it reaches the end of file.Your program appears to be reading and printing each line in the file, and finally printing the value of
strat the bottom. Given that the condition for terminating the read loop is thatstrisnull, that (rather unsurprisingly) is what is printed, and what is returned by the method.