I am currently busy with building a simple javafx application. In this application, you can add and remove .jar files from within the application, from which I am gathering some information. One of the things I use from these .jar files are textures stored as images.
Whenever I load an Image using a path from the jar file, I am unable to remove this .jar file later on. This is quite logical as the .jar file is now being used by this Image, but for some reason, I am unable to delete the .jar file from within the application even when removing all references to this Image and calling the garbage collector.
The way I am currently trying to delete the file is the following:
File file = new File("mods/file.jar");
file.delete();
At some point in the application I initialize the image as follows:
Image block = new Image(pathToJar);
I have tried the following things to resolve my problem:
- Set
block = null;
and callSystem.gc();
- Call
Image.cancel()
and callSystem.gc();
- I have also tried the above in combination with
System.runFinalization();
- I tried removing the .jar file when the stage is closing in hopes of everything being unloaded, but without success.
At this point in time, I am not quite sure why I am unable to actually delete the .jar file. Could anyone possibly explain to me why this is the case and how it could be resolved? Many thanks in advance!
EDIT: the purpose of the application was not clear enough. I am making a color picker that takes average colors of textures from .jar files (Minecraft mods). These .jar files are to be added and deleted from the application in a flexible way. Once you do not want to consider textures of a certain .jar file anymore, you just remove it from the application and be done with it. For ease of use, I made copies of the .jar files so I can access them relatively. Once you are done with the .jar file I want to remove this copy as it will just take in unnecessary storage.
I have narrowed the problem (thus far) down to the initialization of an Image. On request, here a MRE:
public class example extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
// Read image, needed at some point in my code
Image block = new Image("jar:File:./mods/botania.jar!/assets/botania/textures/blocks/alfheim_portal.png");
// Make it so that jar is not used anymore
block.cancel();
block = null;
System.gc();
// Try to delete the file after being done with it
File delete = new File("mods/botania.jar");
Files.delete(delete.toPath());
}
}
After initializing the image, and thereafter removing references to it, it should be cleaned by the garbage collector (at least to my knowledge). Instead, now it just gives the following error:
Caused by: java.nio.file.FileSystemException: mods\botania.jar: The process cannot access the file because it is being used by another process.