字符串在bufferedreader之后返回null
我从一个url中的文本文件中获取一行作为字符串,该字符串返回正确的值。 但是,如果我在读取后调用字符串,则字符串返回null。
我不知道发生了什么,并希望得到任何指导。
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
。
您的程序似乎正在读取并打印文件中的每一行,最后在底部打印str
的值。 鉴于终止读循环的条件是str
为null
,那么(相当不足为奇)是打印的内容,以及方法返回的内容。
Hai Buddy.Look at u’r do-while循环。
do { str = r.readLine(); if (str != null) System.out.println(str); } while (str != null); //ie exit loop when str==null
因此,循环外的str为null
你循环到文件末尾
do { str = r.readLine(); if (str != null) System.out.println(str); //returns correct string } while (str != null);
因此,之后str
为null
。
而不是do while loop
使用while loop
来检查适当的条件并打印结果字符串。
Example construct: BufferedReader in = new BufferedReader(new FileReader("C:/input.txt")); while ((str = in.readLine()) != null) { //write your logic here. Print the required string. }