Java Scanner类hasNext()方法BUG

问题描述 投票:-1回答:1

Scanner hasNext()方法有什么问题?当hasNext()方法读取空的txt文件并获取false时,我将文件写入文件并使用hasNext()重新检查,但这次它再次返回false。但是,当我删除if(hasNext())块时,它工作正常。我怀疑由于s.hasNext()方法而出现问题。 Scanner课程中有错误吗?

public static void main(String[] args) throws Exception {
File file= new File("file.txt");

FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw);

FileReader fr = new FileReader(file);
Scanner s = new Scanner(fr);

if (s.hasNext()) {  // RETURNS FALSE GOES TO ELSE OK(because file is empty)
      //doSomething();
} else{
    pw.println(1);  // WRITE SOMETHING TO FILE
    pw.close();
    System.out.println(s.hasNext());  // returns FALSE AGAIN
    int num = s.nextInt();
    System.out.println("LOOP: " + num + " ***");
    s.close();
}

}

java io java.util.scanner inputstream filereader
1个回答
1
投票

如果要检查扫描仪对象会发生什么,可以尝试在else块中检查.hasNext()的值。我想它应该是假的(就像你在if语句中检查它一样)。

看起来你必须在else语句中创建一个新的Scanner,因为第一个没有捕获文件中的更改。据我所知,这不是一个错误,而是API的决定。

以下示例可以证实我的理解:

public class ScannerTest {

  public static void main(final String[] args) throws IOException {
    final File file = new File("testFile.txt");
    file.delete();

    final PrintWriter printWriter = new PrintWriter(new FileWriter(file, true));

    final Scanner scanner = new Scanner(file);

    System.out.println(scanner.hasNext()); // prints false because the file is empty
    printWriter.write("new line");
    printWriter.close();
    System.out.println(scanner.hasNext()); // prints false because the file is still empty for the first scanner

    // We instantiate a new Scanner
    final Scanner scannerTwo = new Scanner(file);
    System.out.println(scannerTwo.hasNext()); // prints true
  }
}

如果我们查看各个Scanner构造函数的javadoc,我们可以发现:

构造一个新的Scanner,它生成从指定文件扫描的值。

正如我所解释的那样,在实例化Scanner的情况下扫描文件,稍后扫描程序实例无法捕获文件的更改。这就是为什么有必要创建一个新的Scanner实例来读取更新的文件。

© www.soinside.com 2019 - 2024. All rights reserved.