tylercurtiscook tylercurtiscook - 2 years ago 231
Java Question

IllegalStateException: zip file closed during file write

This bug occurs when my program enters the shutdown hook and tries to write the settings file to a text document. The strange thing is, it doesnt throw an exception everytime.

Exception in thread "Thread-4" java.lang.IllegalStateException: zip file closed
at java.util.zip.ZipFile.ensureOpen(Unknown Source)
at java.util.zip.ZipFile.getEntry(Unknown Source)
at java.util.jar.JarFile.getEntry(Unknown Source)
at java.util.jar.JarFile.getJarEntry(Unknown Source)
at com.crimson.server.JarClassLoader.findJarEntry(JarClassLoader.java:514)
at com.crimson.server.JarClassLoader.findJarClass(JarClassLoader.java:584)
at com.crimson.server.JarClassLoader.loadClass(JarClassLoader.java:956)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.crimson.universalUtils.Datastore.store(Datastore.java:66)
at com.crimson.server.ServerShutdownHook.run(ServerShutdownHook.java:38)

Here is Datastore.store(Settings):

public static File set = new File("settings.properties");

public static void store(Settings settings){

try {
PrintWriter pw = new PrintWriter(set);//line 66

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block


I dont know why creating the PrintWriter calls ClassLoader.loadClass, but that could be the problem because im using JarClassLoader: http://www.jdotsoft.com/JarClassLoader.php

Answer Source

I checked the source code of JarClassLoader and the problem is that JarClassLoader also has a shutdown hook to close the jar file. And as the documentation of shutdown hooks says, they may be invoked in any order, or even in parallel. So when your hook "gets in" before JarClassLoaders, your code works. When it's a bit too late, you get this exception.

A way to get around this would be to ensure the PrintWriter class is loaded before invoking the shutdown hook.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download