开发者

String returning null after bufferedreader

开发者 https://www.devze.com 2023-02-17 16:13 出处:网络
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 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() {
    Stri开发者_StackOverflow社区ng 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 returns null when 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 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.


Hai Buddy.Look at u'r do-while loop.

do {
        str = r.readLine();
        if (str != null)
          System.out.println(str);  
      } while (str != null); //i.e exit loop when str==null

So,str outside the loop is null


You loop until end of file within

do {
    str = r.readLine();
    if (str != null)
      System.out.println(str);  //returns correct string
} while (str != null);

Thus afterwards str is null.


Instead of a do while loop use a while loop to check for appropriate condition and print the resultant string.

   Example construct:           

   BufferedReader in = new BufferedReader(new FileReader("C:/input.txt"));          
   while ((str = in.readLine()) != null) {            
   //write your logic here. Print the required string.          
   }           
0

精彩评论

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

关注公众号