访问值While While循环

时间:2013-10-29 08:28:52

标签: java string file

我正在读取整个文件,如果它包含特定字符串,我想使用该行。我无法使用该字符串,因为它在while循环之外打印null,尽管我已经在循环外部初始化它。

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 个答案:

答案 0 :(得分:2)

请尝试以下操作,您必须使用另一个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

答案 1 :(得分: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 时退出。所以你有答案!

答案 2 :(得分: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
     }
 }

这样做,如果你想在循环中打印,

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

答案 3 :(得分:0)

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