[英]Reading a text file with java
我正在编写“移至最前”编码器,该编码器读取给定的文件,然后将文件解析为列表。 它可以很好地与编码配合使用,但是仅适用于只有一行的文件,我认为问题出在while循环中。
这是代码:
while ((line = br.readLine()) !=
null) // While the line file is not empty after reading a line from teh text file split the line into strings
{
splitArray = line.split(" ");
}
for (int i = 0; i <= splitArray.length - 1;
i++) // for every string in the array test if it exists already then output data accordinly
{
if (FirstPass.contains(splitArray[i])) {
System.out.println(FirstPass.lastIndexOf(splitArray[i]));
FirstPass.addFirst(splitArray[i]);
FirstPass.removeLastOccurrence(splitArray[i]);
} else if (!FirstPass.contains(splitArray[i])) {
FirstPass.addFirst(splitArray[i]);
System.out.println("0 " + splitArray[i]);
}
}
System.out.println(" ");
for (String S : FirstPass) {
System.out.println(S);
}
您解析splitArray的代码在while循环之外..因此,仅最后一行会得到处理。
要处理每一行,请将整个for ()
块放入while循环内。
while((line = br.readLine()) != null) // While the line file is not empty after reading a line from teh text file split the line into strings
{
splitArray = line.split(" ");
for(int i = 0; i <= splitArray.length - 1; i++) // for every string in the array test if it exists already then output data accordinly
{
//..........
} // end for
} // end while
大括号放在错误的位置:
while((line = br.readLine()) != null)
{
splitArray = line.split(" ");
} // This } shouuldn't be here...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.