文本文件hasNext()上的扫描程序是无限的

我正在用Java编写一个简单的程序,它需要从文本文件中读取数据。 但是,我在计算线路时遇到了麻烦。 对于简单的谷歌搜索来说,这个问题看起来很通用,但我甚至可能找不到合适的东西。

我正在学习的教科书建议,要计算文本文件中的行数,你应该这样做:

public static int[] sampleDataArray(String inputFile) throws IOException { File file = new File(inputFile); Scanner inFile = new Scanner(file); int count = 0; while (inFile.hasNext()) count++; int[] numbersArray = new int[count]; inFile.reset(); for (int i = 0; i < count; i++) { numbersArray[i] = inFile.nextInt(); } inFile.close(); return numbersArray; } 

在我看来, while (inFile.hasNext())行是问题所在。 我认为hasNext()无限运行。 我在代码中使用的数据文件肯定具有有限数量的数据行。

我该怎么办?

第一次调用hasNext() ,如果你没有从文件中读取, hasNext()将始终返回true。 因为输入的正面没有变化。

想象一下,你有一个包含这一行的文件:

这是输入

如果在此文件上调用hasNext() ,它将返回true因为文件中有下一个标记,在本例中为单词this

如果在初始调用之后没有从文件中读取,则要处理的“下一个”输入仍然是单词this 。 在您从文件中读取之前,下一个输入不会更改。

TL; DR

当你从文件中调用hasNext() ,你将总是有一个无限循环。

另外

如果你真的想使用hasNext() ,或者想要,你可以创建另一个Scanner对象并读取文件来计算行数,那么你的循环就可以了。 另外,你应该真的使用hasNextLine()

 public int countLines(File inFile) { int count = 0; Scanner fileScanner = new Scanner(inFile); while(fileScanner.hasNextLine()) //if you are trying to count lines { //you should use hasNextLine() fileScanner.nextLine() //advance the inputstream count++; } return count; } 

希望这有用。

inFile.hasNext()不会将指针移动到下一行

尝试这个

 String x=null; while((x = inFile.next()) != null) count++; 

hasNext()的描述

如果此扫描器的输入中有另一个标记,则返回true。 在等待输入扫描时,此方法可能会阻塞。 扫描仪不会超过任何输入。

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#hasNext%28%29

要计算行数,请使用hasNextLine() ,而不是hasNext()
while循环中,你应该调用nextLine() ,因为在你当前的实现中,扫描程序在第一行是静态的。 调用此方法将使其在循环的每次迭代中移动到下一行。

请参阅以下代码段:

 while (inFile.hasNextLine()){ inFile.nextLine() count++; } 

您无法使用扫描仪计算文件中的行数,因为默认扫描程序使用空格来分隔标记。 我建议使用BufferReader和readline方法。

http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html

 private Integer getNoOfLines( String fileName) throws FileNotFoundException, IOException { FileInputStream fstream = new FileInputStream(fileName); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; List lineList = new ArrayList(); while ((strLine = br.readLine()) != null) { lineList.add(strLine); } in.close(); return lineList.size(); }