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

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


当前回答

对于windows,引号是必需的,并且;应作为分离器使用。例如:

java -cp "target\\*;target\\dependency\\*" my.package.Main

其他回答

如果使用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/

对于windows,引号是必需的,并且;应作为分离器使用。例如:

java -cp "target\\*;target\\dependency\\*" my.package.Main

如果您确实需要动态指定所有的.jar文件,您可以使用shell脚本或Apache Ant。有一个名为commons Launcher的公共项目,基本上可以让你将启动脚本指定为蚂蚁构建文件(如果你明白我的意思)。

然后,你可以指定如下内容:

<path id="base.class.path">
    <pathelement path="${resources.dir}"/>
    <fileset dir="${extensions.dir}" includes="*.jar" />
    <fileset dir="${lib.dir}" includes="*.jar"/>
</path>

在启动构建文件中,该文件将使用正确的类路径启动应用程序。

在Windows下,这是有效的:

java -cp "Test.jar;lib/*" my.package.MainClass

这是行不通的:

java -cp "Test.jar;lib/*.jar" my.package.MainClass

注意*.jar,因此*通配符应该单独使用。


在Linux操作系统下,如下所示:

java -cp "Test.jar:lib/*" my.package.MainClass

分隔符是冒号而不是分号。

简单回答: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不鼓励这种行为,我想我应该对此进行扩展。