java - 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
循环永远不会发生,但是在调试时,代码工作正常。
我知道这指向线程问题,但我没有明确创建任何线程,而且这个项目甚至不需要多个线程。难道我做错了什么?我该怎么做才能让这段代码正常工作?
解决方案
我猜,您的代码读取了一个新生成的文件,其中内容尚未刷新,因此没有行。在调试中,线程有更多时间写入文件并刷新它。
也许您可以使用文件锁来解决这个问题。
推荐阅读
- arrays - numba jit 无法理解数组的单个元素不是数组
- fipy - 我如何表达像扩散项这样的术语?
- node.js - 如何根据查询值链接 express-validator?
- javascript - 浏览器开发者工具(F12模式)下直接执行Cypress命令如何打印日志
- excel - 删除新工作簿中的空白行
- python - openpyxl:合并单元格的左右边框
- vb.net - 调整窗口大小和窗口窗体
- kubernetes - 具有容器原生负载平衡的 GKE Ingress 未检测到运行状况检查(字段“resource.httpHealthCheck”的值无效)
- angular - 常规变更日志自定义模板 - 如果未指定关闭,则不返回行
- amazon-web-services - 编排中的线程与容器