Building a java classpath from a windows batch file

A great feature introduced with the JDK 6 is the improved classpath syntax for including Jars of a specific directory. This allows you to do this

javac -cp "lib\*"
java -cp "lib\*" MyClass

from the command line without using a build system like Maven or Ant. But each of you who has to build and run Java classes with the JDK 5 or earlier and suffer from some project restrictions that reduces the set of tools to the ordinary command line will have to build the proper classpath by naming each Jar separately:

javac -cp "lib\jar1.jar;lib\jar2.jar"
java -cp "lib\jar1.jar;lib\jar2.jar" MyClass

On a Unix based system one could use glob in a shell script. The doomed Windows users can either use some shell replacements or have to build the command line with the arguable help of batch files. This blog post serves as a reference for those who stumble across loops and delayed expansion of variables in Windows batch files. To make the story of a bumpy road short here is the working solution for Windows XP:

REM needed to overcome weird loop behavior
REM in conjunction with variable expansion
SETLOCAL enabledelayedexpansion

REM construct classpath of seperate jars

FOR %%F IN (lib/*.jar) DO (
  SET cp=!cp!;lib/%%F%

javac -cp "%cp%"
java -cp "%cp%" MyClass

Please note that you should select the needed Jars carefully since Windows XP cannot handle environment variables longer than 8KB. Try to use relative files names to “solve” this issue. If relative paths are no option you could try to use virtual drive letters instead.

Anyway, my advice is: Convince your “build manager” that you need a true build system in order to ensure the product quality and safe hours of work (around) time. In Eclipse a first draft of such an Ant script could be produced using “Export… Ant Buildfiles”.

Support my Work

Writing an article like the one you have just read takes me quite an amount of my personal time. Way too often, I invest this time in different interests and decide against another blog post. On the other hand, you can motivate me with your feedback, your thoughts and your ideas. Please leave a comment below or flattr this post if you think it's worth it.


  1. Actually, I was able to convince the build manager to use Ant for building and runnung java classes;)

    I cannot see any references to javac in the overview of app launcher. Have you ever used this tool to build class files?

  2. Toss Koll says:

    Hi, nice quick ref, but why is forward slash used insted of back one (in the for cycle)?

Leave a Reply