Safely close/remove file for ImageView in JavaFX

流过昼夜 提交于 2019-12-24 15:16:40

问题


I have a JavaFX application which displays all images from a certain folder in a VBox. The VBox is built like this:

try (DirectoryStream<Path> stream = Files.newDirectoryStream(imagePath)) {
    for (Path file : stream) {
        String fileNameLc = file.toString().toLowerCase();
        if (fileNameLc.matches(".*\\.(jpg|png)")) {
            ImageView graph = new ImageView(new Image(Files.newInputStream(file)));
            graph.setPreserveRatio(true);
            imageVBox.getChildren().add(graph);
        }
    }
} catch (IOException ex) {
    //
}

There also is a button to remove all images (and all other files) in the folder which are displayed in the VBox. This is the code for the button action:

imageVBox.getChildren().clear();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(imagePath)) {
    for (Path file : stream) {
        Files.delete(file);
        System.out.println("Removing: " + file);
    }
} catch (IOException ex) {
    //
}

Displaying the images works fine, but deleting them does not work. In the standard output I see

Removing: /foo/img1.jpg
Removing: /foo/img2.jpg
...

No Exceptions are thrown, but the image files are still there if check the contents of the folder. All files in the folder which are not images (and are not displayed in the VBox) are removed succesfully, but the images displayed in the VBox are not.

I thinks the cause is that after

imageVBox.getChildren().clear();

a background thread starts to remove the images and the .clear() method returns immediately. This way the code block which removes the files is executed before the Image resources are closed.

What would be be the best way to close the images? and why is there no Exception thrown by the Files.delete() method?


回答1:


I know it's a realy old question, but i think anyone can have the same problem, i have it few days ago.

The problem is realy simple when you create yout ImageView, the image are load by JAVA, and you can't delete it before free the memory.

I don't know why they are no error, but you can see an error if you try to delete the image file manualy during the execution of jar.

For free the ImageView you have to do that :

Image graph = new Image(Files.newInputStream(file));
ImageView graphView = new ImageView(graph);

graph = null;
graphView.setImage(null);
System.gc();

Don't forget System.gc(), that will call the garbage collector and he will free memory and after that you can now delete the file.

Enjoy,

Sorry for the realy bad english



来源:https://stackoverflow.com/questions/26325996/safely-close-remove-file-for-imageview-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!