用java读取文本文件

时间:2013-04-09 23:15:03

标签: java string parsing arraylist

我正在编写一个“Move To Front”编码器,它读取给定的文件,然后将文件解析为列表。它适用于编码,但它只适用于只有一行的文件,我认为问题出在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);
}

2 个答案:

答案 0 :(得分:0)

解析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 

答案 1 :(得分:0)

错误地点括号:

while((line = br.readLine()) != null) 
{
    splitArray = line.split(" ");
}  // This } shouuldn't be here...