9

I created new modules for software written in java. This software is run from jar file.My classes are extending the classes in this software. I want to write a plugin which adds new classes to the jar file. I know how to extract a jar file to the directory and add them to the jar file using java.util.jar package but as there are a lot of files to extract from the file, is it possible to add new classes without extracting the files to the folder, somehow directly.

user1574866
  • 275
  • 2
  • 6
  • 12
  • 1
    I'm reminded of minecraft modding. Out of curiosity, did you write this software you're trying to extend yourself? There are better ways to do it in that case, using dynamic class loading. – Wug Aug 03 '12 at 18:19
  • There is no need to modify an existing jar file. Just put the classes in their own jar and make sure both jars are on the classpath. – Jim Garrison Aug 03 '12 at 18:21
  • Possible duplicate by the same user: http://stackoverflow.com/questions/11852954/changing-code-at-runtime-in-java – Simon Forsberg Oct 19 '12 at 12:10

3 Answers3

16

You can use the following command

jar uf foo.jar foo.class
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
  • 1
    This works only 50% since that command won't put the class in its corresponding package tree structure. – m0skit0 Oct 10 '16 at 14:48
  • 6
    @m0skit0 To put class in tres structure you need to pass class name with directory structure. jar uf foo.jar /com/test/foo.class – Bhavik Ambani Oct 11 '16 at 08:42
  • `u` option updates an existing jar `c` option create a new archive. So, I need to check whether file exist or not accordingly I'll use u/c. – Davut Gürbüz May 21 '20 at 09:55
7
jar uf jar-file input-file(s)

Will allow to add new files/update existing files in jar without extracting.

kosa
  • 65,990
  • 13
  • 130
  • 167
7

Your question indicates that you want to do this programmatically, not using the command-line jar tool.

From the docs it appears that you'll at least need to get a JarInputStream from an existing JarFile, iterate over the entries using getNextJarEntry, and write to a JarOutputStream with the entries, also adding your own new files using new JarEntry objects for each new file.

Here's sample code for writing a jar from scratch programmatically, this should extend nicely to your case, the difference being that most of the JarEntry objects will be coming from a JarInputStream.

pb2q
  • 58,613
  • 19
  • 146
  • 147
  • From what I understood of the code, we create new class files in the jar and read the contents via stream from the original class files and write them in the newly created class files in the jar. Isn't there an approach that directly copies the class file as a whole and put in the jar, instead of transferring the bytes manually? – Ridhuvarshan Aug 02 '18 at 10:44