Setting multiple jar files within a directory in the Java classpath

Is there a way to include all the jar files within a directory in the classpath?

I’m trying java -classpath lib/*.jar:. my.package.Program and it is not able to find class files that are certainly in those jars. Do I need to add each jar file to the classpath separately?

If you’re using Java 6 (which you should be), Sun added classpath wildcards but you have to get the syntax JUST right. See Classpath. Jump down to the section, “Understanding class path wildcards”

If using Java 6 or later, classpath wildcards are a part of the JVM.

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

 

Key gotchas:

 

Use quotes

Use * only, not *.jar

The above example and gotchas are from other answers on this page. (Thanks davorp et al & Wim Deblauwe)

 

From the Classpath document section entitled, Understanding class path wildcards:

 

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.

Under windows this works:

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

and this does not work:

 

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

notice the *.jar, so the * wildcard should be used alone.

 

On Linux, the following works:

 

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

The separators are colons instead of semicolons.