Sunday, February 28, 2010

modifying JAR files

Ever been in the situation where you just had to make changes to a JAR file? For whatever reason you cannot make a new JAR but have to change the one that you have ? I had to recently replace a class file inside a JAR file and this is the learning from that.

What's the bid deal you ask? Why not just use Winzip or WinRAR.. those can open up JAR files. Well, you can open the JARs up, but you can't fix them once you've broken them. If the need is to have a JAR file you can place on your build path, sneaking in a class file and the zipping it up wont work. No matter how cute you try to get naming your zipped file. The reason this does not work is that every JAR has a manifest file automatically created in it. And Winzip just doesn't play right with manifest files.

What you need to do is use the JAR utility that comes with JDK. This way you can insert you class file and create a new JAR that your application can pick up.

1) use the following command to "unzip" or expand your jar:

> jar xf .jar

This will cause the contents of the JAr to be extracted in the current directory.

2) Make your changes .. replace class file.. whatever.

3) use the following command to "zip" or create your new jar:

jar cf jar-file input-file(s)/folder

Of course, the Sun site has detailed information.

You could also use the u parameter to update only the files you need.
jar -uf .jar

5 comments:

  1. my problem is:
    i extracted jar file and did change in a class file,, i created jar file again from "jar cf" command,i also included the same menifest file used in that jar file...but when i opened jar file,it gave error....i'v also tried to compile that class file by decompiling the class file,changes to source code and again compiled it..at compiling time it is not giving any error...also i can include that class file in jar file...but when i use that jar file in mobile,it open first and when i try to access any feature or property it gives "java/lang/ClassFormatError: Bad version information" error...anyone can plz suggest how to solve it....my email address is
    mkgogra@gmail.com

    ReplyDelete
    Replies
    1. Amazing & Great informative blog,it gives very useful practical information to developer like me. Besides that Wisen has established as Best Java Online Training India . or learn thru Online Training mode Java Online Training From India . Nowadays Hibernate ORM has tons of job opportunities on various vertical industry.

      Delete
  2. more info abouy this topic go to this site

    www.airtelguru.wapsite.me

    ReplyDelete
  3. @Manoj:
    i dont know a lot about this sub but u said u had included the same menifest file.
    u should not include the same file.
    th sdk will create a new file for this new version.
    try this

    ReplyDelete