1

我正在读取整个文件,如果它包含特定字符串,我想使用该行。我无法使用该字符串,因为它null在 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

请帮忙。

4

4 回答 4

3

在下面试试这个,你必须使用另一个 String 或 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
于 2013-10-29T08:32:59.833 回答
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. 所以你有你的答案!

于 2013-10-29T08:29:43.970 回答
0

要停止,您的循环需要wflnull,所以当您的循环刚刚停止时,wfl显然是null

于 2013-10-29T08:35:27.550 回答
0

因为您的 wbf.readLine 在读取 null 时,它也将其分配给 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
于 2013-10-29T08:30:28.463 回答