Wednesday, December 26, 2007

Code Smart: Solution to classpath too long (aka input line too long) problem in Windows

If you use Java in Windows, you're bound to run into classpath too long problem when your classpath grows. Windows has a limit (1KB - 2KB) of characters you can have on one single command line. The infamous "Input line is too long" is very annoying. Here's a trick to get around it.

"java.exe" command also scan for classes from the environment variable "CLASSPATH". If you can break your classpath into separate folders and jars, you can concatenate them like this:


setlocal

set CLASSPATH=c:/my/first/jar/somejar.jar;%CLASSPATH%
set CLASSPATH=c:/my/second/jar/someotherjar.jar;%CLASSPATH%
set CLASSPATH=c:/path/to/a/folder;%CLASSPATH%
.......
.......

java com.mycompany.Main

endlocal

By using CLASSPATH env variable, you don't need to pass it in to "java" command. The setlocal/endlocal pair ensures the CLASSPATH is "local" to this process and won't pollute the systemwise value.

--------
Updated:

Travis has pointed out that there is a limit on environment variable in Windows. I found it limited to 8K. So this isn't an absolute solution but it should sustain you for awhile. As suggested by D, you could shorten the path by using virtual drive. Further more, JDK6 has supported wildcard (*) in classpath.

Virtual drive:
Say you have bunch of jars under c:/path/to/lib

subst z: c:/my/path/to/lib
set CLASSPATH=z:/jar1.jar:%CLASSPATH%

Or with JDK6:

set CLASSPATH=c:/path/to/lib/*:%CLASSPATH%

No comments: