Java
Classpath
JAR Files
Programming
Directory Management

Including all the JARs in a directory in the Java classpath

Codemia Knowledge Hub ·

Use a wildcard on the command line: java -cp "lib/*" com.example.MainClass adds every JAR in lib to the classpath. Wildcards are supported from Java 6 onward. They do not work in a JAR manifest's Class-Path, where each JAR must be listed, so the alternatives are scripts or a build tool.

The classpath tells the JVM and the Java compiler where to find user-defined classes and packages, including dependencies shipped as JAR files.

1. Wildcard on the command line

bash
java -cp "lib/*" com.example.MainClass

All JAR files in the lib directory are added to the classpath. MainClass is the application's entry point, in the package com.example.

2. Class-Path in the manifest file

If your application is itself packaged as a JAR, you can put classpath entries in its manifest, which is more permanent than a command-line flag:

plaintext
Manifest-Version: 1.0
Class-Path: lib/some-library.jar lib/another-library.jar
Main-Class: com.example.MainClass

Only the listed JARs from lib are included. Manifest classpath definitions do not support wildcards, so including a whole directory means listing every JAR explicitly, which is error-prone and does not scale in larger projects.

3. Building the classpath with a script

A script can collect every JAR dynamically.

On Unix-like systems, this joins all JARs in lib with the : separator:

bash
JARS=$(echo lib/*.jar | tr ' ' ':')
java -cp "$JARS:build/classes" com.example.MainClass

On Windows, this batch script does the same with the ; separator:

batch
1@echo off
2SETLOCAL EnableDelayedExpansion
3set "CP=build\classes"
4for %%j in (lib\*.jar) do set "CP=!CP!;%%j"
5java -cp "%CP%" com.example.MainClass
6ENDLOCAL

Performance and maintenance

  • Performance: a large number of JAR files can affect class-loading time. Applications with extensive dependencies may need performance monitoring and profiling.
  • Maintenance: as dependencies grow, use a dependency management tool such as Maven or Gradle, which resolves dependencies automatically.

Comparing the methods

MethodPlatformEase of UseScalabilityMaintenance
Command Line (with wildcard)AllEasyMediumLow
Manifest FileAllMediumLowMedium
ScriptingSpecificHardHighHigh
Dependency Management ToolsAllHardHighHigh

For simple projects or quick setups, the command-line wildcard is enough. For larger projects, scripting or a build system such as Maven or Gradle is usually more efficient.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms