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=latin1You need to download the JDBC driver library for MySQL in order to run the program.
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:
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
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
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:
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 c option is for creating a JAR file.
The f option specifies the JAR file name.
The m option 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.
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.
Other Java Tools Tutorials:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
StudentProgramDemo.zip | [A project illustrates using javac, jar and java tools] | 1211 kB |