Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you compile Java code at command prompt?

Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.


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

Please try on Linux

javac -cp jarfile source file 

EXAMPLE :-

javac  -cp .:/jars/* com/template/*.java

Syntax will work on windows dos command:

javac -cp ".;first.jar;second.jar;third.jar" MyJavaFile.java

The followings are steps,

  1. Copy all jars and your .java file in a same folder (It will be easy to mention file names instead of mentioning long path. Though you can keep jar and .java in separate folders).

  2. To compile,

    javac -cp .:<file_1_name>.jar:<file_2_name>.jar <prog_name>.java
    
  3. To execute,

    java -cp .:<file_1_name>.jar:<file_2_name>.jar <prog_name>
    

I hope this helps!