Something You May Not Know about Jar Command: Part 3

8. jar command options can start with optional -. jar tvf a.jar is the same as jar -tvf a.jar

9. You would usually use relative paths for source files, relative to the current directory. These relative paths will be preserved inside the target jar file. For example, jar cvf \tmp\b.jar com\javahowto\test\ will create the directory tree com\javahowto\test\ inside the target jar, and include all files under <current-dir>\com\javahowto\test\.

If you use absolute paths for source files, jar will copy the absolute paths inside the jar file, which is not what you want. For example,
C:\tmp > jar cvf a.jar C:\tmp\A.class
added manifest
adding: C:/tmp/A.class(in = 405) (out= 279)(deflated 31%)
10. If source files are not located in the current directory, you can use -C option to tell jar command to implicitly change to another directory and then include files there. For example,
C:\ws\nb\scrap\dist > jar cvf hello-world.jar -C ..\build\classes com\javahowto\test
11. If you use -C ../build/classes option and want to include all files under ../build/classes, use . (dot) to represent all files there. Note that you can't use *, which will resolve by OS to all files to the current directory. For example,
C:\ws\nb\scrap\dist > jar cvf hello-world.jar -C ..\build\classes .
The following example (using -C and *) will ignore -C option and instead include all files in the current directory, which is not what we want:
C:\ws\nb\scrap\dist > jar cvf hello-world.jar -C ..\build\classes *
..\build\classes\com\hello-world.jar : no such file or directory
added manifest
adding: scrap.jar(in = 20487) (out= 7472)(deflated 63%)
12. There are 3 types of paths in jar command:
  • path to the destination jar file, either relative or absolute path is fine. In fact, any format is ok as long as it can be correctly resolved by the OS

  • path to the manifest file, if m option is present. Either relative or absolute path is fine. The same as destination file.

  • multiple paths to source files. They should be relative to the current directory, unless -C option is present. In that case, all source files should be relative to the value of -C option.
If you don't like using -C option, I'd suggest you always cd into the parent directory of all source files, and then run jar command.

13. It is not possible to include source files from multiple different parent directories. But you can always first copy them into a common parent directory. Jar task in Apache Ant is more flexible and can accommodate almost all use cases.

14. In JDK 6 or newer version, you can use e option to specify an entry-point class (Main-Class in META-INF/MANIFEST.MF) for self-contained applications packaged in a jar file. See this post for details.

Followers

Pageviews Last 7 Days