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?
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.
Please try on Linux
javac -cp jarfile source file
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,
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).
javac -cp .:<file_1_name>.jar:<file_2_name>.jar <prog_name>.java
java -cp .:<file_1_name>.jar:<file_2_name>.jar <prog_name>
I hope this helps!
Try to add all dependency jar files to your class path through environment variable settings or use the below steps:
- Open command prompt.
- Change directory to the location of you java
file that you would like compile.
Set the classpath for your dependency jar files as shown below:
set classpath=C:Userssarath_sivanDesktopjarsservlet-api.jar; C:Userssarath_sivanDesktopjarsspring-jdbc-3.0.2.RELEASE; C:Userssarath_sivanDesktopjarsspring-aop-3.0.2.RELEASE;
Now, you may compile your java file. (command:
Hope this will resolve your dependency issue.
This will create .class file:
javac -classpath "[jarname with specified path]" [java filename]
This will execute class file:
java -cp [jarname with specified path]: [java filename]
javac -cp .:jars/jar1:jars/jar2:jars/jar3 com/source/*.java
javac -cp jars/jar1:jars/jar2:jars/jar3 abc.java
With -cp command we specify the path where to find the additional libraries which are required to compile the class. jar1, jar2 and jar3, available in jars folder are used to compile abc.java class.
You need to specify the dependencies in compile time as well as runtime
To compile use this format
javac -cp "*.jar;classfile_path" filename.java
javac -cp "ojdbc6.jar;c:programs" Main.java
some times making following change works:
java -cp ".;%CLASSPATH%" classfilename
Note: ON Windows. For linux use
/opt/JavaServices/sqlite $ export CLASSPATH=/opt/JarFiles/XXXX.jar:/opt/JarFiles/XXXX.jar:/opt/JavaServices/;javac SQLiteSample.java