Java package in cmd

How to compile, package and run a Java program using command-line tools (javac, jar and java)

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

1. Organizing Directories Structure

directory structure

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)
  • li b : 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 .
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(); >> > >

2. Compile the program using javac command

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:

compiled files directory

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:

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:

final directory structure

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

java -jar StudentsInsert.jar

Enter the inputs when requested. The following screenshot depicts the running of this program:

command prompt

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:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Читайте также:  Перемещение страницы в java
Оцените статью