从命令行运行JAR文件并指定classpath [英] Run a JAR file from the command line and specify classpath

查看:1129
本文介绍了从命令行运行JAR文件并指定classpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编译了 JAR 文件,并在清单中指定了Main-Class(我使用Eclipse 函数)。我的依赖都在一个标签为 lib 的目录中。我不能得到一个直接的答案如何执行我的JAR文件,同时指定它应该使用 lib / * 作为类路径。



我试过:

 ] $ java -jar -cp::lib / * MyJar .jar 
] $ java -cp::lib / * -jar MyJar.jar
] $ java -cp::lib / * com.somepackage.subpackage.Main



等...






错误:找不到或加载主类....


或指定未找到库的 NoClassDefFoundError



我甚至尝试重新创建JAR文件并包含 lib 目录和内容,但仍然没有骰子...



如何从命令行执行JAR文件并指定要使用的类路径?

解决方案

当您指定 -jar 时, -cp 参数将被忽略。



文档


当您使用此选项时,JAR文件是所有用户类的源,其他用户类路径设置被忽略。


您也不能将所需的jar文件包含到另一个jar文件中(您需要提取其内容, .class文件到您的jar文件中)



您有两个选项:


  1. lib 目录中的所有jar文件包含到清单中(可以使用相关路径)

  2. 包括您的jar)在命令行使用 -cp

    java -cp MyJar.jar:lib / * com.somepackage.subpackage.Main


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.

I've tried:

]$ java -jar -cp .:lib/* MyJar.jar
]$ java -cp .:lib/* -jar MyJar.jar
]$ java -cp .:lib/* com.somepackage.subpackage.Main

etc...

Each gives an error saying:

Error: Could not find or load main class ....

or gives the NoClassDefFoundError indicating the libraries are not being found.

I even tried remaking the JAR file and included the lib directory and contents, but still no dice...

How can I execute a JAR file from the command line and specify the classpath to use?

解决方案

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

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)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

这篇关于从命令行运行JAR文件并指定classpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆