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

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

Leave a Comment