How to include jar files with java file and compile in command prompt

user1177567 picture user1177567 · Feb 22, 2012 · Viewed 319.1k times · Source

I have 3 jar files and a .java file that depends on these jar files. How do I compile the .java file with these jar files using a command prompt?

Answer

kensen john picture kensen john · Feb 22, 2012

You can include your jar files in the "javac" command using the "-cp" option.

javac -cp ".:/home/path/mail.jar:/home/path/servlet.jar;" MyJavaFile.java

Instead of "-cp" you could also use "-classpath"

javac -classpath ".:/home/path/mail.jar:/home/path/servlet.jar:" MyJavaFile.java

You could including the jars every time you compile by setting the environment variable "CLASSPATH" correctly. The environment variable will store the path where the jars and classes that needs to be used for compiling/executing any java file. You will not have to include the jars individually every time you compile you file.

Different machines have different methods to set the classpath as an environment variable. The commands for Windows, Linux, etc are different.

You can find more details in this blog.

http://javarevisited.blogspot.com/2011/01/how-classpath-work-in-java.html