Search code examples
javajar

Editing .jar file by removing dependent jars and then replacing them


I am working on a task that would remove two dependent .jars from a master .jar and then adding them back to the original .jar. It might not make sense, but there is a reason why this is needed.

The original structure of a jar is something like this:

project.jar
-- SUBFOLDER  
-- classes   
-- lib
     -- dependency1.jar
     -- dependency2.jar
     -- dependencyN.jar

I need to remove dependency1.jar and dependency2.jar from the original jar and then add them back.

When I remove the dependencies, the jar runs, but some of the functionalities of the application won't - that's fine. When I add the jars back, that's where the application doesn't work at all.

I tried to use jar utility jar -uf project.jar dependency1.jar dependedncy2.jar, zip utility, I also tried to unzip the jars and only add classes to the project.jar.

I am getting the following error when trying to execute with the updated Jars:

Exception in thread "main" java.lang.IllegalStateException: Failed to get nested archive for entry BOOT-INF/lib/Dependency1.jar at org.springframework.boot.loader.archive.JarFileArchive.getNestedArchive(JarFileArchive.java:104) at org.springframework.boot.loader.archive.JarFileArchive$NestedArchiveIterator.adapt(JarFileArchive.java:237) at org.springframework.boot.loader.archive.JarFileArchive$NestedArchiveIterator.adapt(JarFileArchive.java:228) at org.springframework.boot.loader.archive.JarFileArchive$AbstractIterator.next(JarFileArchive.java:189) at org.springframework.boot.loader.ExecutableArchiveLauncher.createClassLoader(ExecutableArchiveLauncher.java:87) at org.springframework.boot.loader.Launcher.launch(Launcher.java:55) at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:88) Caused by: java.io.IOException: Unable to open nested jar file 'BOOT-INF/lib/Dependency1.jar' at org.springframework.boot.loader.jar.JarFile.getNestedJarFile(JarFile.java:288) at org.springframework.boot.loader.jar.JarFile.getNestedJarFile(JarFile.java:274) at org.springframework.boot.loader.archive.JarFileArchive.getNestedArchive(JarFileArchive.java:100) ... 6 more Caused by: java.lang.IllegalStateException: Unable to open nested entry 'BOOT-INF/lib/Dependency1.jar'. It has been compressed and nested jar files must be stored without compression. Please check the mechanism used to create your executable jar file at org.springframework.boot.loader.jar.JarFile.createJarFileFromFileEntry(JarFile.java:314) at org.springframework.boot.loader.jar.JarFile.createJarFileFromEntry(JarFile.java:296) at org.springframework.boot.loader.jar.JarFile.getNestedJarFile(JarFile.java:285) ... 8 more

It seems like compression is the issue there - is there a good way to manipulate a jar like this?


Solution

  • Using -0 or --no-compress operation modifier solved the issue.

    EXAMPLE: jar -u0f myProject.jar target/directory/Dependency.jar