Dads View

February 1, 2009

Java CLASSPATH headaches

Filed under: Java — Administrator @ 11:21 am

Continuing my ongoing saga documenting my path to learning Java I discovered an annoying but probably very common problem building and running Java programs.

The application I’m developing will utilize Xalan to process some XML files.

That’s not important to this discussion except for the fact that I am planning to use XALAN predefined libaries contained in .jar files in my application.

Per the installation instructions I dutifully added the directory containing the libaries(as .jar files) to my exisitng CLASSPATH system variable in Windows XP as follows:

Right click My Computer -> Properties -> Advanced tab -> Environment
Variables button -> Under System Variables click CLASSPATH

I added the following to the end:
;c:\path_to_the_libraries\
and saved it.

Important note:
Always make sure that CLASSPATH begins with . – that’s a period.
This will insure that Java can always find things in the current directory.

So I try to build my application:

javac myapplication.java

and I get a screen full of errors!

myapplication.java:32: package name_of_library does not exist
import name_of_library;

Looks like it isn’t finding the libraries! I check and double check the CLASSPATH. There’s the directory! What’s the problem!

So I discover that both javac and java have command line parameters to specify a path to look for .jar files.

I try

javac -cp c:\path_to_the_libraries\library.jar myapplication.java
java -cp .;c:\path_to_the_libraries\library.jar myapplication

And It works! But Why?

JAVA can only find actual .class files in the directories listed in CLASSPATH. It won’t look inside the .jar files to find classes!
Each .jar or .zip file must be listed separately.

After removing the original addition to my CLASSPATH system I added

;c:\path_to_the_libraries\library.jar

And now

javac myapplication.java
java myapplication

Works like a charm!

A significant aspect of this is that JAVA applications must always be distributed as a complete directory containing programs and libaries, with a script (or batch file) containing the commands to execute it.

Since you probably don’t want to alter CLASSPATH on another system (unless its’ yours), specifying the complete classpath on the javac and java command lines is probably the way to go.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress