JAR - extracting specific files
Asked Answered
T

3

39

I have .class and .java files in JAR archive. Is there any way to extract only .java files from it? I've tried this command but it doesn't work:

jar xf jar-file.jar *.java
Talaria answered 22/9, 2014 at 11:22 Comment(3)
Why don't you just extract all the files and delete the ones you don't need?Mindymine
Where does this JAR come from? It's not a good practice to package the source and the class files in the same JAR...Antimasque
Because it's uglier and slower solution. There's about 10000 files there.Talaria
A
41

You can use the unzip command which accepts wildcards in its arguments (which is not the case of the jar command). Something like this should do the trick ( disclaimer : not tested)

unzip youFile.jar "*.java"
Aspic answered 22/9, 2014 at 11:42 Comment(0)
U
53

From the source:

To extract only certain files from a jar file, supply their filenames:

C:\Java> jar xf myFile.jar foo bar

Using wildcards is a shell thing, and you should not expect it to work when extracting from a JAR file (which, as you've realized, is the case).

What you can do, is supply a list of the files you want to extract, via the @ modifier:

jar xf my.jar @myfiles.lst

where myfiles.lst would be:

com/my/MyClass.java
com/my/MySecondClass.java

This file could easily be created automatically with creative use of jar tvf, awk and your desired extraction pattern. I'll leave that as an exercise and/or another SO question :-)

Or you could use unzip - a JAR file is basically a zip-file.

Cheers,

Uni answered 22/9, 2014 at 11:29 Comment(1)
Ok I know it, this is in documentation, but does jar support any regexes? I've not found it anywhere:/Talaria
A
41

You can use the unzip command which accepts wildcards in its arguments (which is not the case of the jar command). Something like this should do the trick ( disclaimer : not tested)

unzip youFile.jar "*.java"
Aspic answered 22/9, 2014 at 11:42 Comment(0)
C
-1

jar -xf mylib.jar test.java

The command attempts to extract the file test.java from the JAR file mylib.jar.

Cispadane answered 6/5, 2024 at 2:40 Comment(1)
Yes, but the posted question asks how to extract all the .java files - not just one.Optional

© 2022 - 2025 — McMap. All rights reserved.