Scanner hasNext(( 方法有什么问题?当hasNext((方法读取空的txt文件并得到false,在我向文件写入一些东西并使用hasNext((重新检查之后,但这次它再次返回false。但是当我删除 if(hasNext((( 块时,它可以正常工作。我怀疑问题是由于 s.hasNext(( 方法引起的。扫描程序类中是否有错误?
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();
}
}
如果你想检查你的扫描器对象发生了什么,你可以尝试在你的 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 实例来读取更新的文件。