2011-03-19 80 views
1

我从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; 
    } 

回答

2

当它到达文件末尾的BufferedReader.readLine()方法返回null

您的程序似乎正在读取并打印文件中的每一行,最后在底部打印str的值。假设终止读取循环的条件是strnull,那么打印的内容(而不是出人意料的)就是打印的内容以及该方法返回的内容。

0

你循环,直到文件结尾内

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

因此事后strnull

1

海巴迪。看看你做的循环。

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

因此,外循环str为null取而代之的是do while loop

0

使用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.   
    }