I've downloaded two jars. I want to import some of their contained classes. How do I do this?
It's for my algorithms class. I've tried following the instructions on the following site to no avail.
http://algs4.cs.princeton.edu/code/
There's an installer for OSX (I'm running Mountain Lion) which allegedly adds the jars to your classpath. Unfortunately it also installs Dr. Java. I'd rather just use Sublime and Terminal. I assumed it would be easy enough just...
import java.stdlib;
in my Percolation.java file, but javac-ing that program yields a "package stdlib does not exist", as does
import stdlib;
I've added the location of stdlib.jar and algs4.jar to my Terminal CLASSPATH manually via:
export CLASSPATH=$CLASSPATH:/Users/Michael/path/to/jar/algs4.jar:/Users/Michael/path/to/jar/algs4.jar
export CLASSPATH=$CLASSPATH:/Users/Michael/path/to/jar/stdlib.jar:/Users/Michael/path/to/jar/stdlib.jar
I've also attempted
javac -cp $CLASSPATH:/Users/Michael/path/to/jar/algs4.jar:/Users/Michael/path/to/jar/stdlib.jar Percolation.java
But I still get a
javac Percolation.java
Percolation.java:1: cannot find symbol
symbol : class stdlib
location: package java
import java.stdlib;
^
Percolation.java:2: package java.algs4 does not exist
import java.algs4.WeightedQuickUnionUF;
^
What's going on here?
Also is there a way to permanently add those values to my CLASSPATH in OS X mountain lion. I have to perform that command with every new Terminal.
To run an application in a nonexecutable JAR file, we have to use -cp option instead of -jar. We'll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute: java -cp jar-file-name main-class-name [args …]
java classes. To import your files, you need to create an empty Java project. They you either import them one by one (New -> File -> Advanced -> Link file) or directly copy them into their corresponding folder/package and refresh the project.
If you're using Terminal to compile and launch your program, then in the Terminal window, begin by setting the CLASSPATH
:
$ export CLASSPATH=$CLASSPATH:/Users/Michael/path/to/jar1.jar:/Users/Michael/path/to/jar2.jar
Then you can type echo $CLASSPATH
and see that the jars are referenced.
Now, in the same Terminal window, use javac to compile your class. Setting the CLASSPATH
as above only applies to the current Terminal window and any processes launched from it.
Alternately you can pass the CLASSPATH
to javac:
$ javac -cp $CLASSPATH:/Users/Michael/path/to/jar1.jar:/Users/Michael/path/to/jar2.jar MyClass.java
To persist this CLASSPATH
for future Terminal sessions, add the export
line above to the file .profile in your home directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With