简体   繁体   中英

execute jar error could not find or load main class

sorry for another "could not find or load main class" question.

I'm new to Java. I searched for a while but couldn't find the reason.

My project is a very simple one created with maven .

mvn archetype:generate -DgroupId=mycompany -DartifactId=faker -DinteractiveMode=false

pom.xml(default, not change)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>mycompany</groupId>
  <artifactId>faker</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>faker</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

and source code(default, not change)

package mycompany;

public class App {
    public static void main( String[] args ) {
        System.out.println( "Hello World!" );
    }
}

I build jar file with jar command.

~$ jar cvfm MyCompany.jar manifest.txt  src/main/java/mycompany/App.java
# added manifest
# adding: src/main/java/mycompany/App.java(in = 705) (out= 352)(deflated 50%)

manifest.txt

~$ cat manifest.txt 
Main-Class: mycompany.App
# (has an empty new line here)

but whenever I executed it, it give me following error:

~$ java -jar MyCompany.jar 
Error: Could not find or load main class mycompany.App

Where is wrong ?

openjdk version "1.8.0_181"
Apache Maven 3.5.2

Thanks @ohlec and @Kayaman, to be more specific, here's the way to solve it.

# get App.class
~$ cd src/main/java/mycompany/ && javac App.java
# back to faker folder
~$ jar cvfm MyCompany.jar manifest.txt  -C src/main/java mycompany/App.class
~$ java -jar MyCompany.jar
# Hello World!

Your jar should have a directory structure that mirrors the package structure; in your case, src/main/java is included, although that is not a package prefix. Use -C to specify the root directory:

jar cvfm MyCompany.jar manifest.txt  -C target mycompany/App.class

Edit: Also, as Kayaman pointed out, you need to include the .class file, not the .java file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM