从命令行运行 JAR 文件并指定类路径 [英] Run a JAR file from the command line and specify classpath
问题描述
我编译了一个 JAR 文件并在清单(我使用了 Eclipse Export 函数).我的依赖项都在一个标记为 lib
的目录中.我似乎无法直接回答如何执行我的 JAR 文件,同时指定它应该使用 lib/*
作为类路径.
I've compiled a JAR file and specified the Main-Class in the manifest (I used the Eclipse Export function). My dependencies are all in a directory labeled lib
. I can't seem to get a straight answer on how to execute my JAR file while specifying it should use the lib/*
as the classpath.
我试过了:
]$ java -jar -cp .:lib/* MyJar.jar
]$ java -cp .:lib/* -jar MyJar.jar
]$ java -cp .:lib/* com.somepackage.subpackage.Main
等等...
每个都给出一个错误说:
Each gives an error saying:
错误:无法找到或加载主类....
或给出 NoClassDefFoundError
指示未找到库.
or gives the NoClassDefFoundError
indicating the libraries are not being found.
我什至尝试重新制作 JAR 文件并包含 lib
目录和内容,但仍然没有骰子...
I even tried remaking the JAR file and included the lib
directory and contents, but still no dice...
如何从命令行执行 JAR 文件并指定要使用的类路径?
How can I execute a JAR file from the command line and specify the classpath to use?
推荐答案
当您指定 -jar
时,-cp
参数将被忽略.
When you specify -jar
then the -cp
parameter will be ignored.
来自文档:
当您使用该选项时,JAR 文件是所有用户类的来源,其他用户类路径设置将被忽略.
您也不能将所需的 jar 文件包含"到另一个 jar 文件中(您需要提取它们的内容并将 .class 文件放入您的 jar 文件中)
You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)
您有两个选择:
- 将
lib
目录中的所有 jar 文件包含到清单中(您可以在那里使用相对路径) - 使用
-cp
在命令行上指定所有内容(包括您的 jar):java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
- include all jar files from the
lib
directory into the manifest (you can use relative paths there) - Specify everything (including your jar) on the commandline using
-cp
:
java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
这篇关于从命令行运行 JAR 文件并指定类路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!