in our latest project in school, I got some problems. I want to observe a Path for new entries, the path is chosen by a file director button but if I choose any file, the whole window freezes... I guess it got frozen as the "observePath" method got called but I don't know how to fix this problem.
Here's the code:
public void start() {
public Path absolutePath;
final Label labelSelectedDirectory = new Label();
Button btnOpenDirectoryChooser = new Button();
btnOpenDirectoryChooser.setText("Open DirectoryChooser");
btnOpenDirectoryChooser.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
DirectoryChooser directoryChooser = new DirectoryChooser();
File selectedDirectory =
directoryChooser.showDialog(primaryStage);
if(selectedDirectory == null) {
labelSelectedDirectory.setText("No Directory selected");
}else{
labelSelectedDirectory.setText(selectedDirectory.getAbsolutePath());
absolutePath = selectedDirectory.toPath();
try {
observePath();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
});
public void observePath() throws IOException, InterruptedException {
WatchService watcher = FileSystems.getDefault().newWatchService();
FileSystem fs = FileSystems.getDefault();
Path p = fs.getPath(absolutePath.toString());
WatchKey key = p.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
key = watcher.take();
for (WatchEvent event : key.pollEvents()) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("found new data");
}
else {
System.out.println("no new data found");
}
}key.reset();
}
}
I hope someone can help me. Thank you very much
Tom