How to use classes from .jar files?
I read the Java tutorials on Sun for JAR files, but I still can't find a solution for my problem. I need to use a class from a jar file called jtwitter.jar, I downloaded the file, and tried executing it (I found out yesterday that .jar files can be executed by double clicking on them) and Vista gave me an error saying "Failed to load Main-Class Manifest attribute from [path]/jtwitter.jar".
The guy who coded the .jar file wants me to import it, but where do I store the .jar file to import it in my code? I tried putting both the .jar file and my .java file in the same directory, didn't work.
The file I'm trying to work for is here: http://www.winterwell.com/software/jtwitter.php
I'm using JCreator LE.
Let's say we need to use the class Classname
that is contained in the jar file org.example.jar
And your source is in the file mysource.java
Like this:
import org.example.Classname;
public class mysource {
public static void main(String[] argv) {
......
}
}
First, as you see, in your code you have to import the classes. To do that you need import org.example.Classname;
Second, when you compile the source, you have to reference the jar file.
Please note the difference in using :
and ;
while compiling
-
If you are under a unix like operating system:
javac -cp '.:org.example.jar' mysource.java
-
If you are under windows:
javac -cp .;org.example.jar mysource.java
After this, you obtain the bytecode file mysource.class
Now you can run this :
-
If you are under a unix like operating system:
java -cp '.:org.example.jar' mysource
-
If you are under windows:
java -cp .;org.example.jar mysource
Not every jar file is executable.
Now, you need to import the classes, which are there under the jar, in your java file. For example,
import org.xml.sax.SAXException;
If you are working on an IDE, then you should refer its documentation. Or at least specify which one you are using here in this thread. It would definitely enable us to help you further.
And if you are not using any IDE, then please look at javac -cp option. However, it's much better idea to package your program in a jar
file, and include all the required jar
s within that. Then, in order to execute your jar
, like,
java -jar my_program.jar
you should have a META-INF/MANIFEST.MF
file in your jar
. See here, for how-to.