2013-10-29 206 views
1

我在讀整個文件,如果它包含特定的字符串,我想使用該行。我無法使用字符串,因爲它在while循環外面打印null,儘管事實上我已經在循環之外初始化了它。訪問值While While循環

FileInputStream wf = new FileInputStream(pr.getSplitDir() + listfiles[i]); 
BufferedReader wbf = new BufferedReader(new InputStreamReader(wf)); 
String wfl = ""; 
while ((wfl = wbf.readLine()) != null) { 
    if (wfl.contains("A/C NO:")){ 
     // System.out.println(wfl); // Here it is Printing the correct line 
    } 
} 
System.out.println(wfl); // Here it is printing null 

請幫忙。

回答

2

試試這個下面,你必須使用另一個字符串或StringBuilder的得到最終出來把

 FileInputStream wf = new FileInputStream(pr.getSplitDir() + listfiles[i]); 
     BufferedReader wbf = new BufferedReader(new InputStreamReader(wf)); 
     String wfl = ""; 
     StringBuilder sb = new StringBuilder(); 
     while ((wfl = wbf.readLine()) != null) { 
      if(wfl.contains("A/C NO:")){ 
       //System.out.println(wfl);//Here it is Printing the correct line 
       sb.append(wfl); 
      } 
     } 
     System.out.println(sb.toString());//Here it is printing null 
1
while ((wfl = wbf.readLine()) != null) { 
       if(wfl.contains("A/C NO:")){ 
        //System.out.println(wfl);//Here it is Printing the correct line 

       } 
      } 

while循環會退出,只有當wfl is null。所以你有你的答案!

0

因爲當讀空的wbf.readLine,它賦予它WFL太然後比較爲null

while ((wfl = wbf.readLine()) != null) { // here wbf.readLine when read null assigns to wfl 
    if(wfl.contains("A/C NO:")){ 
     //System.out.println(wfl);//Here it is Printing the correct line 
    } 
} 

像這樣做,如果你想while循環外面打印,

String test =""; 
String wfl =""; 
while ((wfl = wbf.readLine()) != null) { 
     if(wfl.contains("A/C NO:")){ 
      //System.out.println(wfl);//Here it is Printing the correct line 
     } 

     test = test + wfl ; // for assigning all line 
     //test = wfl // for assigning last line 
} 



System.out.println(test); // it wil print the correct line 
0

要STO p,你的循環需要wflnull,所以當你的循環剛剛停止時,wfl顯然是null