2012-09-30 55 views
0

为什么不能if (txtLine == null) { break; };工作?或者正确的答案是为什么它仍然将字符串txtLine设置为空(字面意思)。我理解它的方式,它应该打破字符串为空的那一刻?我不希望它将字符串设置为“null”。但停止时,有在* .txt文件没有更多的行java:使用Buffered Reader并检查字符串是否为空

try{ 
    BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt")); 
    while (true) { 
     // Reads one line. 
     println(txtLine); 
     if(txtLine == null){ 
      break; 
     }; 
     txtLine = txtReader.readLine(); 
     nLines(txtLine); 
    } 
    txtReader.close(); 
} catch (IOException ex) { 
    throw new ErrorException(ex); 
} 

txtFile变量定义为伊娃

private int nChars = 0; 
private String txtLine = new String(); 
private ArrayList <String> array = new ArrayList <String>(); 
+2

txtLine在哪里定义?你能否把它添加到你的代码片段? –

+0

如果你通过Java中的'Scanner'或者'BufferedReader'来读取用户输入的内容 - >你会立即得到数以百万计的结果,这将清除你的疑问。 –

+0

nLines做什么? –

回答

3

我认为,当你打破的顺序,当您更改值的txtLine是从文件中读取向后,你的代码应该是这个样子的下一行:

try{ 
    BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt")); 
    while (true) { 
     // Reads one line. 
     println(txtLine); 
     txtLine = txtReader.readLine(); 
     // check after we read the value of txtLine 
     if(txtLine == null){ 
      break; 
     } 

     nLines(txtLine); 
    } 
    txtReader.close(); 
} catch (IOException ex) { 
    throw new ErrorException(ex); 
} 

但是,这是一个更简洁(和余吨hink,更清晰)格式:

try{ 
    BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt")); 
    while ((txtLine = txtReader.readLine()) != null) { 
     // Reads one line. 
     println(txtLine); 
     nLines(txtLine); 
    } 
    txtReader.close(); 
} catch (IOException ex) { 
    throw new ErrorException(ex); 
} 

while ((txtLine = txtReader.readLine()) != null)套txtLine到下一行,然后检查该txtLine没有继续前空。

+0

正确!正如你指出的那样,它是'txtLine = txtReader.readLine();'的顺序。当然,在执行条件检查之前,需要读取新行以检查它是否为空。 –