kellyfj
kellyfj

Reputation: 6943

Is there a quick way to delete a file from a Jar / war without having to extract the jar and recreate it?

So I need to remove a file from a .jar or .war file. I was hoping there was something like jar -d myjar.jar file_I_donot_need.txt

But, right now the only way I can see of doing this from my Linux command line (without using WinRAR/Winzip or the Linux equivalent) is to

Please tell me there is a shorter way.

Upvotes: 134

Views: 133189

Answers (5)

Kirby
Kirby

Reputation: 15855

The best answer for me was in a comment by lapo on another answer on this post.

User lapo wrote:

I more often have p7zip installed instead of zip and in this case it's important to specify file format: 7z d -tzip file.jar dir/unwanted_file.txt

User lapo's comment is in response to an answer suggesting using zip -d directly since the .jar files are like .zip archives but not exactly the same format. Like others, I wasn't able to use zip -d file.jar unwanted_file.txt. That would lead to

zip error: Zip file structure invalid

But, I was able to install p7zip via brew install p7zip, and then I was able to delete using 7z d -tzip file.jar unwanted_file.txt.

Upvotes: 3

Gamebuster19901
Gamebuster19901

Reputation: 176

If you wish to do this programatically, can use the Zip File System to treat zip/jar files as a file system. This will allow you to edit, delete, and add files to the jar file.

See Appending files to a zip file with Java

Upvotes: 0

In case you want to delete file in order to unsign signed jar, you can probably just make the .RSA file zero-sized. This can be accomplished with just jar u. See https://stackoverflow.com/a/24678645/653539 . (Worked for me, though I admit it's hack.)

Upvotes: 3

martona
martona

Reputation: 5914

zip -d file.jar unwanted_file.txt

jar is just a zip file after all. Definitely much faster than uncompressing/recompressing.

Upvotes: 265

Peter Lawrey
Peter Lawrey

Reputation: 533510

In Java you can copy all the entries of a jar except the one you want to delete. i.e. you have to make a copy but don't need to create the individual files.

You can do this by

  • creating a new jar.
  • iterating though the Jar you have
  • copy the entry from one jar to the other, skipping any files you want.
  • close and replace the orginal jar if you want.

Upvotes: 1

Related Questions