2017-08-07 33 views
0

我正在使用以下代码来读取位于我的根项目目录中的.txt文件,但是,我一直遇到输出不包含整个文件的主体。我的代码如下:尝试使用扫描仪读取.txt文件时文本丢失

public void readFile() throws IOException { 
    int index = 0; 
    int indexT = 1; 
    File fileName = new File(file); 
    Scanner inFile = new Scanner(fileName); 
    while (inFile.hasNext()) { 
     String line = inFile.nextLine(); 
     System.out.println(line); 
     if (indexT%3 == 0) { 
      fileList[index] = inFile.nextLine(); 
     } else if (indexT == 1 || indexT == 4 || indexT == 7){ 
      playList[index] = inFile.nextLine(); 
     } else { 
      break; 
     } 
     index++; 
     indexT++; 
    } 
    inFile.close(); 
} 

我已经经历过类似的问题,一直无法确定与我的代码问题。据我所知,它应该是完美的。所有帮助表示赞赏!

回答

3

你有一个逐行阅读线条的循环,但是你在第2行打破了它。它只是不会超出这个范围。

while (inFile.hasNext()) { 
    if (indexT%3 == 0) { 
     //... 
    } else if (indexT == 1 || indexT == 4 || indexT == 7){ 
     //... 
    } else { 
     break; 
    } 
    indexT++; 
} 

indexT公历1,你有一个情况下,则递增。这一次,没有特殊情况,所以它达到“休息”。并跳出循环。所以..没有更多的行被读取。