Error: Could not find or load main class - JAR file

Error: Could not find or load main class - JAR file

我在创建工作 JAR 文件时遇到问题。我可以 运行 我的 .class 文件如下:

$ java -cp build/ example.HelloWorld 
Hello World!

但是 运行作为 jar(在我的构建脚本中)的 ning 失败了:

java -cp build/ -jar dist/HelloWorld.jar
Error: Could not find or load main class example.HelloWorld

我将使用简单的 Hello World 项目来简化我遇到的问题:

.
├── build
│   └── example
│       └── HelloWorld.class
├── build.sh
├── dist
│   └── HelloWorld.jar
└── src
    └── example
        └── HelloWorld.java

class 文件需要放入 build 文件夹中。 JAR 文件需要位于 dist 文件夹中。 build.sh 是构建 JAR 文件的 bash 脚本。这是:

mkdir -p build && \
mkdir -p dist && \                                         
javac -cp src/ src/example/HelloWorld.java -d build && \
jar -cfe dist/HelloWorld.jar example.HelloWorld build/ && \
java -cp build/ -jar dist/HelloWorld.jar

HelloWorld.java:

package example;

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

运行 build.sh 中可以看到的 JAR 文件导致

$ ./build.sh 
Error: Could not find or load main class example.HelloWorld

如前所述,运行直接运行该应用程序效果很好。

这是HelloWorld.jar的结构。

.
├── build
│   └── example
│       └── HelloWorld.class
└── META-INF
    └── MANIFEST.MF

MANIFEST.MF 的内容。

Manifest-Version: 1.0
Created-By: 1.8.0_40 (Oracle Corporation)
Main-Class: example.HelloWorld

我已经工作了大约 6 年,现在只使用 C 和 C++。将我视为 Java 的新手。我真的不知道我做错了什么并且 运行 没有想法 google 并尝试。

您的 JAR 文件结构有误。你不能把 build 目录放在那里。它必须看起来像这样:

.
├── example
│   └── HelloWorld.class
└── META-INF
    └── MANIFEST.MF