We often see jar files, some of which can be run directly, for example, double-click jar files in windows, and use the "Java-jar *. Jar" command in Linux to run jar files,
However, some jar files cannot be double-clicked to run, or the system prompts that there is no main when running the preceding command. The cause is related to the JAR file generation method. Only the class where the main method is specified when the JAR file is generated can it be directly run.
The following describes two common JAR file generation methods:
(1) Specify the entry class when generating jar
For example, the following program is available:
[Root @ localhost javatest] # ls <test. Java is the entry class containing the main method>
Test. Java test. Class
First, create a manifest. MF file, add relevant content, and specify the portal class.
[Root @ localhost javatest] # Vim manifest. MF
Main-class: <space> test <press enter>
Be sure to note: space and press Enter: Main-class: Test
Packaging:
[Root @ localhost javatest] # jar cvfm X. Jar manifest. MF *. Class
You need to package the class file during packaging. You can also select other files.
Run:
[Root @ localhost javatest] # Java-jar javatest. Jar
Because the entry class is specified, the test class in the jar file will be directly run during the runtime.
View the content in the jar file:
Use "jar xvf *. Jar" to decompress the JAR file to the current directory.
Zkl @ hadoopvm01 :~ /Java/Hello> jar xvf X. Jar
Created: META-INF/
Inflated: META-INF/manifest. MF
Inflated: Test. Class
Zkl @ hadoopvm01 :~ /Java/Hello> ls
META-INF test. Class X. Jar
Zkl @ hadoopvm01 :~ /Java/Hello> ls META-INF/
Manifest. MF
Zkl @ hadoopvm01 :~ /Java/Hello> CAT META-INF/manifest. MF
Manifest-version: 1.0
Created-by: 1.6.0 _ 17 (Sun Microsystems Inc .)
Main-class: Test
We can see that there is a META-INF/manifest. MF file, the content of the manifest. MF file is written into the file during packaging.
When running the JAR file, it will also read the file and find the entry class.
(2) The entry class is not specified when jar is generated.
For the above program, first package:
[Root @ localhost javatest] # jar cvf x. jar *. Class
Run:
Because no entry class is specified, the following error occurs in the "Java-jar X. Jar" command:
Failed to load main-class manifest attribute from X. jar.
Decompress the X. jar file to view the content of manifest. MF.
Zkl @ hadoopvm01 :~ /Java/Hello> CAT META-INF/manifest. MF
Manifest-version: 1.0
Created-by: 1.6.0 _ 17 (Sun Microsystems Inc .)
The reason is that a row is missing in the (1) ratio. Run the JAR file as follows.
Zkl @ hadoopvm01 :~ /Java/A> JAVA-classpath X. jar test
In this way, Java searches for the test class in classpath. Here, it searches for more test classes in X. jar and then runs.
Appendix:
(3) Complicated packaging of jar commands
External library path: Lib
Source code path: SRC, with many packages
Path of the class file: Bin