Solace Solace - 8 months ago 14
Java Question

Why am I getting this weird output when creating a JAR file from commandline?

I wrote a HelloWorld class in a folder "D:\Workspaces\Workspace\Packaging Programs into JAR Files\src". I am trying to create a Jar file containing this HelloWorld.class file, following this tutorial. So I opened cmd in the src directory and executed the following command.

jar cv HelloWorld.jar HelloWorld.class

I got this:

D:\Workspaces\Workspace\Packaging Programs i
nto JAR Files\src>jar cv HelloWorld.jar HelloWorld.class
HelloWorld.jar : no such file or directory
δ╗£H ♦ META-INF/■╩ ♥ ☻ PK♥ δ╗£H ¶ ME
K-*╬╠╧│R0╘3ασr.JM,IM╤u¬♦ ÿδ↓─¢[*h°↨%&τñ*8τ↨§Σ↨%û òk≥r±r☺ P╖îqëC D PK♥
c╖£H ► HelloWorld.classmPMK├@►}█|515╡╡⌡│P☼B¶1ŧ/éx(*D⌠α)iù▓%╔JL¶⌂û
7₧GÅQÉD┘ï\d│æ↕:í,≤ ?‼è∞¥≤$æ╖2Oªçèφ┬B╙┬Üïul0┤¬≥┴≡I◄v,l║╪┬6⌡¿e♀φz╠e<τôΓ▼¶>?¶<
┌d∟♀6e♥èîó▒*♫÷B ↓ª╙¼@EYé√G▌%⌐BφW4:┌←⌠ÜεT]5Ω¬‼╥¬ª,* P♥ èY!☺ ⌐☺ PK δ╗£H ☻
♦ META-INF/■╩ PK☺☻¶ δ╗£H╖îqëC D ¶ = ME
TA-INF/MANIFEST.MFPK☺☻¶ c╖£H♥ èY!☺ ⌐☺ ► ┬ HelloWorld.classPK♣♠
♥ ♥ ╗ !☻
D:\Workspaces\Workspace\Packaging Programs i
nto JAR Files\src>

Why is this happening? Did I make a mistake?


You are missing the -f parameter which tells the JAR tool to output to a file rather than the console:

jar cvf HelloWorld.jar HelloWorld.class


You could achieve the same result as above without the -f flag by telling JAR to send the output to the standard output, and then redirecting into the actual JAR file you want. Hence, the following would accomplish the same as above:

jar cv HelloWorld.class > HelloWorld.jar

It should be noted that piping the output from JAR into an output file is a feature of the OS and not a feature of Java.