How to compile, package and run a Java program using command-line tools (javac, jar and java)
- Details
- Written by Nam Ha Minh
- Last Updated on 26 September 2019   |   Print Email
This tutorial helps you use the core tools in JDK (javac, jar and java) to compile, package and run a Java program under the following circumstance:
- The Java source file is under a package.
- There’s an external library.
- The JAR file is an executable JAR.
By following this tutorial step by step, you will be able to use the three tools (javac, jar and java) together fluently in your daily Java programming.
The Java program we use in this tutorial is a JDBC client that connects to a MySQL database named Students and inserts a row into the table students. Here’s the MySQL script to create the database:
create database Students; use Students; CREATE TABLE `student` ( `student_id` int(11) NOT NULL, `name` varchar(45) NOT NULL, `email` varchar(45) NOT NULL, `university` varchar(45) NOT NULL, PRIMARY KEY (`student_id`), UNIQUE KEY `student_id_UNIQUE` (`student_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
You need to download the JDBC driver library for MySQL in order to run the program.
1. Organizing Directories Structure
Create the following director structure on your computer:
The way you organize files is very important, as it affects the readability, maintainability and extensibility of a program when it evolves over times. Therefore it’s recommended to follow a common, standard directory structure as shown in the screenshot above. Let’s understand each directory in details:
- classes: contain compiled classes (.class files)
- lib: contains third-party libraries. Download MySQL Connector JAR file here.
- src: contains source code which is organized in sub directories representing Java packages. Here’s the package is net.codejava and the Java source file is StudentsInsert.java.
And below is source code of the program in the StudentsInsert.java file:
package net.codejava; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.Scanner; /** * * A JDBC client program that inserts a row into a MySQL database. * @author www.codejava.net */ public class StudentsInsert { @SuppressWarnings("resource") public static void main(String[] args) { // Initialising database and connection objects: String dbURL = "jdbc:mysql://localhost:3306/Students"; String username = "root"; String password = "P@ssw0rd"; Connection conn = null; String sql = null; try { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of students: "); int numberOfStudents = scanner.nextInt(); int countInsertion = 0; int countInformationToDisplay = 1; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (countInsertion < numberOfStudents) { System.out.println("Enter information for student #" + countInformationToDisplay + "\t"); System.out.print(""); System.out.print("\tName: "); String name = reader.readLine(); System.out.print("\tEmail: "); String email = reader.readLine(); System.out.print("\tUniversity: "); String university = reader.readLine(); conn = DriverManager.getConnection(dbURL, username, password); // Inserting data to the Student table sql = "INSERT INTO Student (name, email, university) VALUES (?, ?, ?)"; PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, name); statement.setString(2, email); statement.setString(3, university); int rowInserted = statement.executeUpdate(); if (rowInserted > 0) { ++countInsertion; ++countInformationToDisplay; } System.out.println("" + countInsertion + " students saved to database."); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } } catch (Exception ex) { ex.printStackTrace(); } } } }
Now, let’s see how to compile, create JAR and run this program using command line tools
2. Compile the program using javac command
Open command prompt and move the current directory to the StudentProgram.
javac -d classes src\net\codejava\StudentsInsert.java
This command compiles the StudentsInsert.java source file and places the .class files under the classes directory. The -d option is used to specify the output directory containing compiled files. A good thing is that, the Java compiler automatically creates package directories structure in the destination directory, as shown in the following screenshot:
In case the source files reference third-party library (JAR) files, use the -cp option and specify the JAR file. For example:
javac -cp lib\mysql-connector-java-5.1.21-bin.jar -d classes src\net\codejava\StudentsInsert.java
If there are multiple JAR files, they must be separated by semicolon like this:
javac -cp lib\mysql-connector-java-5.1.21-bin.jar;lib\log4j-1.2.17.jar -d classes src\net\codejava\StudentsInsert.java
3. Create executable JAR file using jar command
Before wrapping the compiled files into an executable JAR file, let create manifest.txt file (using a simple text editor such as Notepad on Windows or Vi on Linux) in the current directory (StudentProgram) with the following content:
Main-Class: net.codejava.StudentsInsert
Class-Path: lib\mysql-connector-java-5.1.21-bin.jar
<blank line>
The first line specifies the class will be called when the JAR file gets executed. This class must have main() method. You see the StudentsInsert class is specified with its fully qualified name (including package name).
The second line specifies the third-party libraries referenced by the program. Here we specify the MySQL Connector library JAR file. In case you refer multiple JAR files, separate them by spaces like this:
Class-Path: lib\mysql-connector-java-5.1.21-bin.jar lib\log4j-1.2.17.jar
Here we specify the paths relative to the JAR file being created.
NOTE: There must be a blank line at the end of the manifest file, otherwise it won’t work.
Now type the following command to package the JAR file:
jar cfm StudentsInsert.jar manifest.txt -C classes net
The coption is for creating a JAR file.
The foption specifies the JAR file name.
The moption specifies where to look at the manifest file.
The -C option specifies where to take the .class files. Here we specify the entire package in the classes directory.
You should see the StudentsInsert.jar file created. The whole directory structure would look like this:
NOTE: If the JAR file doesn’t depend on any third-part libraries, we don’t have to create the manifest file. Instead, we can use the e option to specify the main class.
4. Run the program using java command
Now type the following command to execute the newly generated JAR file:
java -jar StudentsInsert.jar
Enter the inputs when requested. The following screenshot depicts the running of this program:
We hope you find this tutorial helpful for your Java development using command line tools. You can download the whole project under the Attachments section to experiment yourself.
Next, let study about Java classes and objects.
Other Java Tools Tutorials:
- javac command examples
- java command examples
- Java jar command examples
- Java serialver command examples
- Understanding the triad tools javac, java and jar in JDK
- The Java Shell (jshell) Tutorial
Comments
Спасибо!
Yes, it's possible to put jars inside jar to make a fat jar called "uber jar". But you should use an IDE to create a fat jar.
Is it possible to include the driver in the jar file so the jar file is a standalone program which doesn't need the /lib directory?
To compile, type: javac hello.java
To run, typeL java hello