首页 > 解决方案 > Scanner.hasNext() 在正常运行时返回 false,但在调试时返回 true

问题描述

一旦在目录中创建文件,我就必须从文件中读取一些信息。这些文件是由另一个程序自动创建的。为此,我使用WatchService来监视文件创建和Scanner读取文件。在 main 方法上,我有一个简单while(true)的,我的Watcher类被调用。这是构造函数:

public Watcher(String srcDir, String targetDir) throws IOException, InterruptedException {
        this.srcDir = Paths.get(srcDir);
        this.targetDir = Paths.get(targetDir);

        this.watcher = this.srcDir.getFileSystem().newWatchService();
        this.srcDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE); // this will check ONLY for new files; no
                                                                             // deletions or modifications
        this.key = this.watcher.take();
    }

以及在主循环中调用的方法(我删除了部分代码,因为它不相关):

public void checkForNewFile() throws IOException {
    String[] info = new String[6];
    if (this.watcher != null) {
        List<WatchEvent<?>> events = this.key.pollEvents();

        newFileName = "";
        for (WatchEvent event : events) {
            // I kept getting errors when trying to get only the last event
            newFileName = event.context().toString();
        }

        if(newFileName != "") {
            System.out.println("opening new file...");
            Scanner scanner = new Scanner(new FileInputStream(srcDir.toString() + "/" + newFileName));

            String line;
            System.out.println(scanner.hasNext());
            while(scanner.hasNext()) {
                line = scanner.nextLine();
                System.out.println("splitting lines...");
                String[] parts = line.split("|");
                ...
            }
            scanner.close();
        }
        this.key.reset();
    }
}

在上面的方法中,当我正常运行程序时,System.out.println(scanner.hasNext());返回false并且while循环永远不会发生,但是在调试时,代码工作正常。

我知道这指向线程问题,但我没有明确创建任何线程,而且这个项目甚至不需要多个线程。难道我做错了什么?我该怎么做才能让这段代码正常工作?

标签: javafilethread-safetyfileinputstream

解决方案


我猜,您的代码读取了一个新生成的文件,其中内容尚未刷新,因此没有行。在调试中,线程有更多时间写入文件并刷新它。

也许您可以使用文件锁来解决这个问题。


推荐阅读