How set CLASSPATH variable for a folder in Ubuntu

First, in general, setting the env var CLASSPATH usually causes more problems than it solves -- since not all app's want/need the same classpath, & often break when undesired or even unneeded jars are included in the classpath. A java app should only include the minimum number of jars it requires, no more, no less.

When you have specific, individual apps that do require that the classpath be set, then usually the command-line option is preferred: java -cp path1:path2:.... Desktop icons can have their command altered to include these options, or shell scripts can be modified to include these options.

That being said (and since there are always exceptions to the rule), then depending on the version of java (this requres java 6 or later), you can specify that a whole directory of jars be added to the classpath by adding a "*" at the end of a directory; e.g, the following:

 /dir1/foo.jar:/dir2/dir3:/dir5/dir6/*:etc...

Means:

  • /dir1/foo.jar - (the single jar) will be added to the classpath;
  • /dir2/dir3 - all un-jar'd classes in this directory will be added to the classpath (must be in proper package structure; e.g, com.my.Foo.class must be in /dir2/dir3/com/my/Foo.class)
  • /dir5/dir6/* - all jars in this directory (i.e., /dir5/dir6/*.jar) will be added to the classpath. Note that this "*" isn't a wildcard (you can't use f*.jar or even *.jar); it's a special character indicating "add all jars"

In general, if you have to add a whole directory of jars to the application's classpath, the app was not bundled correctly. Rather, the app should have a manifest containing the list of jars it depends on. Or at the very least, only one jar should be added to your classpath, and that jar can have in its manifest the whole list of jars in some subdirectory.


if you want to set classpath permanently then 1) find out where java is installed.. you may use "whereis java" openjdk-7/6 is in /usr/lib/jvm/.....

2) we need to set up CLASSPATH in /etc/environment

  sudo gedit /etc/environment

3) add the following likes .. ( DONT LEAVE ANY SPACES WHILE TYPING)(customize according to your java version and installation) (this home path is for open jdk 7)

   JAVA_HOME="/usr/lib/jvm/java-7-openjdk-i386/bin"

   export JAVA_HOME

   CLASSPATH=".:/usr/lib/jvm/java-7-openjdk-i386/lib:/home/laptop/Desktop/a2"

   export CLASSPATH

separate directory by ":"