簡體   English   中英

使用Java讀取文本文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM