`

Building a java classpath from a windows batch file (Reposted)

 
阅读更多

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\*" MyClass.java
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" MyClass.java
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
cp=explicitlyKnownJar1.jar;explicitlyKnownJar2.jar;

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

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

Another Sample:
@echo off
 setLocal EnableDelayedExpansion
 set CLASSPATH="for/R ./lib %%a in (*.jar)do(
   set CLASSPATH=!CLASSPATH!;%%a
 )
 set CLASSPATH=!CLASSPATH!"
 echo !CLASSPATH!

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”.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics