有没有一种方法可以将所有的jar文件包含在类路径的目录中?
我正在尝试java -classpath lib / *。jar :. my.package.Program,它无法找到当然在这些罐子里的类文件。我是否需要将每个jar文件分别添加到类路径中?
使用Java 6或更高版本,classpath选项支持通配符。请注意以下几点:使用直引号(“)”
使用*,而不是*。jar
窗java -cp "Test.jar;lib/*" my.package.MainClass
的Unix
java -cp "Test.jar:lib/*" my.package.MainClass
这与Windows类似,但使用:而不是;。如果不能使用通配符,bash允许使用以下语法(其中lib是包含所有Java归档文件的目录):
java -cp $(echo lib/*.jar | tr ' ' ':')
(请注意,使用类路径与-jar选项不兼容。另请参见:从命令提示符执行带有多个classpath库的jar文件)
了解通配符
从Classpath文件:<
/ p>Class path entries can contain the basename wildcard character *, which is
considered equivalent to specifying a list of all the files in the directory
with the extension .jar or .JAR. For example, the class path entry foo/*specifies all JAR files in the directory named foo. A classpath entry
consisting simply of * expands to a list of all the jar files in the current
directory.
>A class path entry that contains * will not match class files. To match
both classes and JAR files in a single directory foo, use either foo;foo/*or foo/*;foo. The order chosen determines whether the classes and resources
in foo are loaded before JAR files in foo, or vice versa.
>Subdirectories are not searched recursively. For example, foo/* looks for
JAR files only in foo, not in foo/bar, foo/baz, etc.
>The order in which the JAR files in a directory are enumerated in the
expanded class path is not specified and may vary from platform to platform
and even from moment to moment on the same machine. A well-constructed
application should not depend upon any particular order. If a specific order
is required then the JAR files can be enumerated explicitly in the class path.
>Expansion of wildcards is done early, prior to the invocation of a program’s
main method, rather than late, during the class-loading process itself. Each
element of the input class path containing a wildcard is replaced by the
(possibly empty) sequence of elements generated by enumerating the JAR files
in the named directory. For example, if the directory foo contains a.jar,
b.jar, and c.jar, then the class path foo/* is expanded into
foo/a.jar;foo/b.jar;foo/c.jar, and that string would be the value of the
system property java.class.path.
>The CLASSPATH environment variable is not treated any differently from the
-classpath (or -cp) command-line option. That is, wildcards are honored in
all these cases. However, class path wildcards are not honored in the Class-
Path jar-manifest header.
在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
分隔符是冒号而不是分号。
未经作者同意,本文严禁转载,违者必究!