官术网_书友最值得收藏!

Packaging classes into a JAR file

When you deliver a Java application, usually the code is packaged into JAR, WAR, EAR, or some other packaged format. We learn something again that seems to be obscure at first sight, but in reality, this is not that complex. They are all ZIP files. You can open any of these files using WinZip or some other zip manager that you have a license for. The extra requirement is that, for example, in the case of a JAR file, the archive should contain a directory named META-INF and inside it a file named MANIFEST.MF. This file is a text file and contains meta information in the format, which is as follows:

Manifest-Version: 1.0 
Created-By: 9-ea (Oracle Corporation)

There can be a lot of other information in the file, but this is the minimum that the Java provided tool jar puts there if we package our class file into a jar issuing the following command:

         jar -cf hello.jar HelloWorld.class

The -c option tells the JAR archiver to create a new JAR file and the option f is used to specify the name of the new archive. The one we specified here is hello.jar and the file added to it is the class file.

The packaged JAR file can also be used to start the Java application. Java can read directly from JAR archives and load classes from there. The only requirement is that they are on the classpath.

Note that you cannot put inpidual classes on the classpath, only directories. As JAR files are archives with an internal directory structure in them, they behave like a directory.

Check that the JAR file was created using ls hello.jar and remove the rm HelloWorld.class class file just to ensure that when we issue the command line, the code is executed from the JAR file and not the class.

    $ java -cp hello.jar HelloWorld
Hello World

To see the content of the JAR file, however, it is recommended that you use the JAR tool and not WinZip even though that may be cozier. Real professionals use the Java tools to handle Java files.

$ jar -tf hello.jar 
META-INF/
META-INF/MANIFEST.MF
HelloWorld.class
主站蜘蛛池模板: 罗源县| 乌鲁木齐市| 石首市| 白银市| 林西县| 沁源县| 曲沃县| 南华县| 沅陵县| 马关县| 两当县| 昌黎县| 大关县| 惠水县| 筠连县| 广饶县| 穆棱市| 南宫市| 都兰县| 固阳县| 界首市| 乌拉特中旗| 北辰区| 拉萨市| 自治县| 钦州市| 昌乐县| 奇台县| 无为县| 盱眙县| 大悟县| 中宁县| 武邑县| 蓬溪县| 晋州市| 赤城县| 锦州市| 始兴县| 北辰区| 广灵县| 滕州市|