[英]How to access a string value in a while loop, outside of a while loop, all while inside a method
[英]Access value Outside While loop
我正在读取整个文件,如果它包含特定字符串,我想使用该行。 我无法使用该字符串,因为它在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
请帮忙。
尝试下面这个,你必须使用另一个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
while ((wfl = wbf.readLine()) != null) {
if(wfl.contains("A/C NO:")){
//System.out.println(wfl);//Here it is Printing the correct line
}
}
只有当wfl is null
时,你的while循环才会退出 。 所以你有答案!
因为你的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
要停止,你的循环需要wfl
为null
,所以当你的循环刚刚停止时, wfl
显然是null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.