How to use the apache commons java library on Ubuntu?

java

Solution

If you can compile it with

javac -cp commons-lang3-3.1.jar Randstr.java

then you can run it with

java -cp commons-lang3-3.1.jar:. Randstr

The JAR file has to be in the classpath.

Problem

I am a Java beginner and trying to figure out how to use the apache commons lib. Here is a source file `Randstr.java`: ``` import org.apache.commons.lang3.RandomStringUtils; class Randstr { public static void main(String[] args) { String s = RandomStringUtils.random(12); System.out.println(s); } } ``` I have the `commons-lang3-3.1.jar` file in /usr/share/java/ and have created a symlink in the current dir. Then I compiled it like this: `javac -cp commons-lang3-3.1.jar Randstr.java`, the complilation was fine, but when I execute `java Randstr`, I got the following error: ``` Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/RandomStringUtils at Randstr.main(Randstr.java:5) Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang3.RandomStringUtils at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 1 more ``` And if I don't specify the jar file in the classpath, it will not even compile: ``` javac -cp . Randstr.java # Randstr.java:1: error: package org.apache.commons.lang3 does not exist # import org.apache.commons.lang3.RandomStringUtils; # ^ # Randstr.java:5: error: cannot find symbol # String s = RandomStringUtils.random(12); # ^ # symbol: variable RandomStringUtils # location: class Randstr # 2 errors javac -cp /usr/share/java/ Randstr.java # Randstr.java:1: error: package org.apache.commons.lang3 does not exist # import org.apache.commons.lang3.RandomStringUtils; # ^ # Randstr.java:5: error: cannot find symbol # String s = RandomStringUtils.random(12); # ^ # symbol: variable RandomStringUtils # location: class Randstr # 2 errors ``` From reading other questions on stackoverflow, I see this can be solved by using an IDE, but I prefer a simple editor at the moment.

Original source