是否有一种方法将所有jar文件包含在类路径的目录中?

我正在尝试java -classpath lib/*.jar:。program,它不能找到在这些罐子里的类文件。我是否需要将每个jar文件分别添加到类路径中?


当前回答

简单回答:java -classpath lib/*:。my.package.Program

Oracle提供了关于在Java 6和Java 7的类路径中使用通配符的文档,在“理解类路径通配符”一节中。(在我写这篇文章的时候,这两页的内容是一样的。)以下是此次会议的重点总结:

In general, to include all of the JARs in a given directory, you can use the wildcard * (not *.jar). The wildcard only matches JARs, not class files; to get all classes in a directory, just end the classpath entry at the directory name. The above two options can be combined to include all JAR and class files in a directory, and the usual classpath precedence rules apply. E.g. -cp /classes;/jars/* The wildcard will not search for JARs in subdirectories. The above bullet points are true if you use the CLASSPATH system property or the -cp or -classpath command line flags. However, if you use the Class-Path JAR manifest header (as you might do with an ant build file), wildcards will not be honored.

是的,我的第一个链接与得分最高的答案中提供的链接相同(我没有希望超越它),但这个答案并没有提供更多的解释。由于现在Stack Overflow不鼓励这种行为,我想我应该对此进行扩展。

其他回答

您需要分别添加它们。或者,如果确实需要指定一个目录,可以将所有内容解jar到一个目录中,并将其添加到类路径中。但是,我不推荐这种方法,因为您可能会在类路径版本控制和不可管理性方面出现奇怪的问题。

macOS,当前文件夹

Java 13在macOS Mojave…

如果所有的.jar文件都在同一个文件夹中,使用cd将其设置为当前工作目录。与pwd核实。

对于-classpath,首先必须列出应用程序的JAR文件。使用冒号:作为分隔符,附加星号*以获得同一文件夹中的所有其他JAR文件。最后,将类的完整包名与main方法一起传递。

例如,对于一个名为my_app.jar的JAR文件中的一个应用程序,在一个名为com的包中一个名为app的类中有一个主方法。例如,在同一个文件夹中放置一些需要的罐子:

java -classpath my_app.jar:* com.example.App

如果使用Java 6,则可以在类路径中使用通配符。

现在可以在类路径定义中使用通配符:

javac -cp libs/* -verbose -encoding UTF-8 src/mypackage/*.java  -d build/classes

裁判:http://www.rekk.de/bloggy/2008/add-all-jars-in-a-directory-to-classpath-with-java-se-6-using-wildcards/

来自wepapp的类:

  > mvn clean install

  > java -cp "webapp/target/webapp-1.17.0-SNAPSHOT/WEB-INF/lib/tool-jar-1.17.0-SNAPSHOT.jar;webapp/target/webapp-1.17.0-SNAPSHOT/WEB-INF/lib/*" com.xx.xx.util.EncryptorUtils param1 param2

以适合多个jar和当前目录的类文件的方式设置类路径。

CLASSPATH=${ORACLE_HOME}/jdbc/lib/ojdbc6.jar:${ORACLE_HOME}/jdbc/lib/ojdbc14.jar:${ORACLE_HOME}/jdbc/lib/nls_charset12.jar; 
CLASSPATH=$CLASSPATH:/export/home/gs806e/tops/jconn2.jar:.;
export CLASSPATH