是否有一种方法将所有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不鼓励这种行为,我想我应该对此进行扩展。

其他回答

简单回答: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到一个目录中,并将其添加到类路径中。但是,我不推荐这种方法,因为您可能会在类路径版本控制和不可管理性方面出现奇怪的问题。

java命令的参数顺序也很重要:

c:\projects\CloudMirror>java Javaside -cp "jna-5.6.0.jar;.\"
Error: Unable to initialize main class Javaside
Caused by: java.lang.NoClassDefFoundError: com/sun/jna/Callback

c:\projects\CloudMirror>java -cp "jna-5.6.0.jar;.\" Javaside
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable

我在一个文件夹里有多个罐子。下面的命令在JDK1.8中对我有用,可以包括文件夹中的所有jar。请注意,如果在类路径中有空格,请在引号中包含

窗户

“C:\My Jars\sdk\lib\*

运行:java -classpath "C:\My Jars\sdk\lib\*; C:\ programs" MyProgram

Linux

编译:javac -classpath "/home/guestuser/My Jars/sdk/lib/*" MyProgram.java

运行:java -classpath "/home/guestuser/My Jars/sdk/lib/*:/home/guestuser/programs" MyProgram

请注意,在Windows上的Java 7中,通配符展开被打破了。

查看这个StackOverflow问题以获得更多信息。

解决方法是在通配符后面加一个分号。Java -cp " where/*;"