Java Tools Tutorialshttps://codejava.net/java-core/toolsSun, 05 May 2024 00:51:03 -0500Joomla! - Open Source Content Managementen-gbJava jar command exampleshttps://codejava.net/java-core/tools/using-jar-command-exampleshttps://codejava.net/java-core/tools/using-jar-command-examples

In this Java tools tutorial, I will help you understand how to use the jar command provided in the Java Development Kit (JDK) with various useful examples.

Table of contents:

    1. Creating a normal jar file
    2. Including/Excluding manifest file in the jar file
    3. Creating an executable jar file
    4. Viewing content of a jar file
    5. Updating content of a jar file
    6. Extracting content of a jar file
    7. Disabling compression for jar file
    8. Generating index information for jar file
    9. Using command line argument files
    10. Passing JRE options

You know, jar is Java archive tool that packages (and compresses) a set of files into a single archive. The archive format is ZIP but the file name usually has .jar extension. This tool is used for creating, updating, extracting and viewing content of jar files.

The executable file of this tool can be located under the JDK_HOME\bin directory (jar.exe on Windows), so make sure you include this path in the PATH environment variable in order to run this tool anywhere from the command line prompt.

The general syntax of jar command is as follows:

jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...

Type jar command without any arguments to see its syntax and options, or see the online documentation here. In this tutorial, we summarize the most common usages of the jar command for your quick reference. Suppose that we have a project with the following directory structure:

Directory structure

The following examples demonstrate how to use the jar tool to create a library jar file, create an executable one and view, update, and extract content of the generated jar file. In most cases, the current directory is SwingEmailSender.

 

1. Creating a normal JAR file

A normal jar file is the non-executable one, such as a library jar file or an applet jar file. The following command put all files under the build\classesdirectory into a new jar file called SwingEmailSender.jar:

jar cfv SwingEmailSender.jar -C build\classes .

Note that there is a dot (.) at the end which denotes all files. The c option is to create, the f is to specify jar file name, the v is to generate verbose output, and the -C is to specify the directory containing the files to be added. Here’s the output (some entries are removed for brevity):

added manifest
adding: net/(in = 0) (out= 0)(stored 0%)
adding: net/codejava/(in = 0) (out= 0)(stored 0%)
adding: net/codejava/swing/(in = 0) (out= 0)(stored 0%)
adding: net/codejava/swing/FileTypeFilter.class(in = 1019) (out= 589)(deflated 42%)
adding: net/codejava/swing/JFilePicker.class(in = 2369) (out= 1195)(deflated 49%)
adding: net/codejava/swing/mail/(in = 0) (out= 0)(stored 0%)
adding: net/codejava/swing/mail/ConfigUtility.class(in = 1689) (out= 907)(deflated 46%)
adding: net/codejava/swing/mail/EmailUtility.class(in = 2451) (out= 1210)(deflated 50%)
adding: net/codejava/swing/mail/SwingEmailSender.class(in = 5695) (out= 2881)(deflated 49%)

In case the current directory is build\classes, the -C option can be omitted (but the jar file needs to be moved upward two levels). For example:

jar cfv ..\..\SwingEmailSender.jar .

If we want to add only files in a specific package:

jar cfv SwingEmailSender.jar -C build\classes net\codejava\swing\mail

That takes only files in the package net.codejava.swing.mail (recursively).

The following command adds only one class (SwingEmailSender.class) to the jar file:

jar cfv SwingEmailSender.jar -C build\classes net\codejava\swing\mail\SwingEmailSender.class

If we want to add multiple classes, separate them by spaces (with full path). Suppose that the current directory is build\classes, the following command adds two classes (SwingEmailSender.class and JFilePicker.class) to the jar file:

jar cf ..\..\SwingEmailSender.jar net\codejava\swing\mail\SwingEmailSender.class net\codejava\swing\JFilePicker.class


2. Including/Excluding manifest file in the JAR file

By default, the jar tool automatically creates a manifest file when generating a new jar file. If we don’t want to have the manifest created, use the M option as in the following example:

jar cfvM SwingEmailSender.jar -C build\classes .

In case we want to manually add an external manifest file, use the m option as in the following example:

jar cfm SwingEmailSender.jar manifest.txt -C build\classes .

Here, content of the manifest.txt is copied to the generated manifest file inside the jar file.

 

3. Creating an executable JAR file

An executable jar file (stand-alone desktop application) must have information about the application entry point (main class) defined in its manifest file. The entry point can be specified either directly on the command line (using the e option), or in an external manifest file.

The following command creates an executable jar file with the main class is net.codejava.swing.mail.SwingEmailSender:

jar cfe SwingEmailSender.jar net.codejava.swing.mail.SwingEmailSender -C build\classes .

If using an external manifest file, remember to specify the main class by adding the following entry to the manifest file. For example:

Main-Class: net.codejava.swing.mail.SwingEmailSender

And the following command creates an executable jar file with the main class is specified in the external manifest file (manifest.txt):

jar cfm SwingEmailSender.jar manifest.txt -C build\classes .

 

4. Viewing content of a JAR file

The t option is used in conjunction with the f and v to list table of contents of a jar file. For example:

jar tf SwingEmailSender.jar

Output:

META-INF/
META-INF/MANIFEST.MF
net/
net/codejava/
net/codejava/swing/
net/codejava/swing/FileTypeFilter.class
net/codejava/swing/JFilePicker.class
net/codejava/swing/mail/
net/codejava/swing/mail/ConfigUtility.class
net/codejava/swing/mail/EmailUtility$1.class
net/codejava/swing/mail/EmailUtility.class
net/codejava/swing/mail/SettingsDialog.class
net/codejava/swing/mail/SwingEmailSender.class

Adding the v option will include file size and date time for each entry. For example:

jar tfv SwingEmailSender.jar

Output:

     0 Tue Dec 03 20:26:02 ICT 2013 META-INF/
    68 Tue Dec 03 20:26:02 ICT 2013 META-INF/MANIFEST.MF
     0 Tue Dec 03 14:30:36 ICT 2013 net/
     0 Tue Dec 03 14:30:36 ICT 2013 net/codejava/
     0 Tue Dec 03 14:30:36 ICT 2013 net/codejava/swing/
  1019 Thu May 23 06:43:08 ICT 2013 net/codejava/swing/FileTypeFilter.class
  2369 Thu May 23 06:43:08 ICT 2013 net/codejava/swing/JFilePicker.class
     0 Tue Dec 03 14:30:36 ICT 2013 net/codejava/swing/mail/
  1689 Thu May 23 06:43:08 ICT 2013 net/codejava/swing/mail/ConfigUtility.class
  2451 Thu May 23 06:43:08 ICT 2013 net/codejava/swing/mail/EmailUtility.class
  3700 Thu May 23 06:43:08 ICT 2013 net/codejava/swing/mail/SettingsDialog.class
  5695 Thu May 23 06:43:08 ICT 2013 net/codejava/swing/mail/SwingEmailSender.class

It’s also possible to list only files under a specific package. The following command lists only files under the package net.codejava.swing.mail:

jar tf SwingEmailSender.jar net/codejava/swing/mail

Output:

net/codejava/swing/mail/
net/codejava/swing/mail/ConfigUtility.class
net/codejava/swing/mail/EmailUtility.class
net/codejava/swing/mail/SettingsDialog.class
net/codejava/swing/mail/SwingEmailSender.class

 

5. Updating content of a JAR file

The u option is used to update an existing jar file, e.g. adding new classes and removing/updating manifest file.

The following example adds/updates the classes under the package net.codejava.swing.download to the existing archive:

jar uf SwingEmailSender.jar -C build\classes net/codejava/swing/download

The following command updates everything but removes the manifest file:

jar ufM SwingEmailSender.jar -C build\classes .

And the following command updates everything including the manifest file:

jar ufm SwingEmailSender.jar manifest.txt -C build\classes .

 

6. Extracting content of a JAR file

To extract a jar file, use the x option in conjunction with the f and v. The following command extracts all content of the SwingEmailSender.jar file to the current directory:

jar xf SwingEmailSender.jar

Add the v option if we want verbose output:

jar xfv SwingEmailSender.jar

Output:

  created: META-INF/
 inflated: META-INF/MANIFEST.MF
  created: net/
  created: net/codejava/
  created: net/codejava/swing/
 inflated: net/codejava/swing/FileTypeFilter.class
 inflated: net/codejava/swing/JFilePicker.class
  created: net/codejava/swing/mail/
 inflated: net/codejava/swing/mail/ConfigUtility.class
 inflated: net/codejava/swing/mail/EmailUtility.class
 inflated: net/codejava/swing/mail/SettingsDialog.class
 inflated: net/codejava/swing/mail/SwingEmailSender.class

If we want to extract only files under a specific package, pass the package path after the jar file name. For example:

jar xfv SwingEmailSender.jar net/codejava/swing/mail

That extracts only files in the package net.codejava.swing.mail. Here’s the verbose output:

  created: net/codejava/swing/mail/
 inflated: net/codejava/swing/mail/ConfigUtility.class
 inflated: net/codejava/swing/mail/EmailUtility.class
 inflated: net/codejava/swing/mail/SettingsDialog.class
 inflated: net/codejava/swing/mail/SwingEmailSender.class

 

7. Disabling compression for JAR file

By default, the generated jar file is compressed as ZIP/ZLIB compression format. However, it’s possible to disable the default compression by specifying the 0 option. For example:

jar cfv0 SwingEmailSender.jar -C build\classes .

 

8. Generating index information for JAR file

The i option allows us to generate an INDEX.LIST file that contains information about the specified jar file, such as the dependent jar files and location of all packages. For example:

jar i SwingEmailSender.jar

The INDEX.LIST file is generated under the META-INF directory. Here’s a sample content of this file:

JarIndex-Version: 1.0

SwingEmailSender.jar
net
net/codejava
net/codejava/swing
net/codejava/swing/download
net/codejava/swing/mail

 

9. Using command line argument files

This is a useful feature that shortens and simplifies a lengthy jar command line. Just create a text file that contains jar options and arguments (separated by spaces or new lines), and then execute the jar command in the following form:

jar @file1 @file2...

For example, create a classes.txt file containing the classes to be included as follows:

net/codejava/swing/mail/ConfigUtility.class
net/codejava/swing/mail/EmailUtility.class
net/codejava/swing/mail/SwingEmailSender.class

Then execute the following command:

jar cfv SwingEmailSender.jar -C build\classes @classes.txt

Create an options.txt file that contains all the options as follows:

cfve SwingEmailSender.jar
net.codejava.swing.mail.SwingEmailSender
-C build\classes

Then execute the following command:

jar @options.txt @classes.txt

 

10. Passing JRE options

The -J option allows us to pass options to the underlying Java Runtime Environment (JRE) when needed. For example:

jar cfv SwingEmailSender.jar -C build\classes . -J-Xmx128M

That passes the option -Xmx128M (maximum memory size is 128MB) to the runtime environment. Note that there must be no space between -J and the options.

 

References:

 

Other Java Tools Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)ToolsWed, 04 Dec 2013 01:06:34 -0600
javac command exampleshttps://codejava.net/java-core/tools/using-javac-commandhttps://codejava.net/java-core/tools/using-javac-command

In this Java tools tutorial, you will learn how to use the Java compiler via the javac command to compile Java source files (.java) into bytecode files (.class).

Table of content:

    1. Compile a single Java source file
    2. Compile multiple Java source files
    3. Compile a Java source file which has dependencies
    4. Specify destination directory
    5. Specify source path directory
    6. Specify Java source compatibility version
    7. Specify target VM version
    8. Silent compilation and verbosity

You know, the Java Development Kit (JDK) provides javac which is the Java compiler program. It compiles Java source files (.java) into bytecode class files (.class). The tool is located under JDK_HOME\bin directory. So make sure you included this directory in the PATH environment variable so it can be accessed anywhere in command line prompt.

This tutorial summarizes common practices for compiling Java source files from command line. All the commands below are supposing the current working directory is where the source files are placed. Syntax of this command is:

javac [options] [source files]

Type javac -help to view compiler options, and type javac -version to know current version of the compiler. By default, the generated .class files are placed under the same directory as the source files.

 

1. Compile a single Java source file

javac HelloWorld.java 

 

2. Compile multiple Java source files

  • Compile three source files at once, type:
    javac Program1.java Program2.java Program3.java

     

  • Compile all source files whose filenames start with Swing:
    javac Swing*.java

     

  • Compile all source files:
javac *.java 

 

3. Compile a Java source file which has dependencies

It’s very common that a Java program depends on one or more external libraries (jar files). Use the flag -classpath(or -cp) to tell the compiler where to look for external libraries (by default, the compiler is looking in bootstrap classpath and in CLASSPATH environment variable).

  • Compile a source file which depends on an external library:
    javac -classpath mail.jar EmailSender.java


    Or:

    javac -cp mail.jar EmailSender.java
  • Compile a source file which depends on multiple libraries:
    javac -cp lib1.jar;lib2.jar;lib3.jar MyProgram.java

    Or we can use the wildcard character *:

    javac -cp *; MyProgram.java

    That will instruct the compiler to look for all available libraries in the same directory as the source file.

 

4. Specify destination directory

Use the -d directoryoption to specify where the compiler puts the generated .class files. For example:

javac -d classes MyProgram.java

 

NOTES:

      • The compiler will complain if the specified directory does not exist, and it won’t create one.
      • If the source file is under a package, the compiler will create package structure in the destination directory.

 

5. Specify source path directory

We can tell the compiler where to search for the source files by using the -sourcepath directoryoption. For example:

javac -sourcepath src MyProgram.java

 

That will compile the MyProgram.java file in the src directory.

 

6. Specify Java source compatibility version

We can tell the compiler which Java version applied for the source file, by using the -source release option. For example:

javac -source 1.5 MyProgram.java

 

That will tell the compiler using specific language features in Java 1.5 to compile the source file. The valid versions are: 1.3, 1.4, 1.5 (or 5), 1.6 (or 6) and 1.7 (or 7).

 

7. Specify target VM version

The compiler can generate the .class files for a specific Java virtual machine (VM) version. Using the -target release option we can do this, for example: 

javac -target 1.6 -source 1.5 MyProgram.java

 

The target VM version must be greater than or equal the source version, that’s why we specify both the options -target and -source here.

By default, the target VM version is the version of the compiler.

 

8. Silent compilation and verbosity

The compiler can compile source files which are related to the specified one, and it does that silently. So using the -verbose option can tell us what the compiler is doing:

javac -verbose MyProgram.java


Other Java Tools Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)ToolsTue, 22 Jan 2013 11:20:10 -0600
java command exampleshttps://codejava.net/java-core/tools/examples-of-using-java-commandhttps://codejava.net/java-core/tools/examples-of-using-java-command

In this Java tools tutorial, I will guide you how to use the java command provided in JDK (Java Development Kit) to execute Java programs.

Table of content:

    1. Run a Java program from a .class file
    2. Running a Java program from an executable jar file
    3. Specify splash screen
    4. Set system properties
    5. Specify memory size

You know, java is the Java application launcher tool which is used to execute programs written in Java programming language and compiled into bytecode class files. Its executable file can be found under JDK_HOME\bin directory (java.exe on Windows and java on Linux), so make sure you include this path to the PATH environment variable in order to invoke the program anywhere in command line prompt.

 

java command syntax:

java [options] file.class [arguments...]

java [options] -jar file.jar [arguments... ]

The first syntax is for executing a class file, and the second one is for executing a JAR file.

Type java -help to consult the available options or browse Oracle’s Java documentation for detailed description and explanation of the options. The arguments, if specified, will be passed into the running program.

 

NOTES:

    • A Java class must have the public static void main(String[] args) method in order to be executed by the Java launcher.
    • An executable JAR file must specify the startup class in by the Main-Class header in its manifest file.

Following are common usage examples of the java tool in daily Java development.

 

1. Run a Java program from a .class file

  • Run a simple class:

If you have a source file called MyProgram.java and it is compiled into MyProgram.class file, type the following command:

java MyProgram 
  • Run a class which is declared in a package:

If the class MyProgram.java is declared in the package net.codejava, change the working directory so that it is parent of the net\codejava directory, then type:

java net.codejava.MyProgram 
  • Run a class which has dependencies on jar files:

    If we have a JavaMail-based program that depends on mail.jar library. Assuming the jar file is at the same directory as the class file, type:

    java -cp mail.jar;. PlainTextEmailSender

    NOTES: There must be a dot (.) after the semicolon.

    If the jar file is inside a directory called lib:

    java -cp lib/mail.jar;. PlainTextEmailSender

    If the program depends on more than one jar files:

    java -cp mail.jar;anotherlib.jar;. MyProgram

    We can use wildcard character to refer to all jar files:

    java -cp *;. MyProgram
    Or:
    java -cp lib/*;. MyProgram

     

  • Passing arguments to the program:

The following example passes two arguments “code” and “java” into the MyProgram:

java MyProgram code java

If the argument has spaces, we must enclose it in double quotes, for example:

java MyProgram "code java" 2013

That will pass two arguments “code java” and “2013”.

 

2. Run a Java program from an executable JAR file

  • Run a standalone jar file:
java -jar MyApp.jar

Here the MyApp.jar file must define the main class in the header Main-Class of its manifest file MANIFEST.MF. The header is usually created by the jar tool.

NOTES: if the jar file depends on other jar files, the reference jar files must be specified in the header Class-Path of the jar’s manifest file. The -cp option will be ignored when using -jar flag.

  • Passing arguments:

Pass two arguments “code” and “java” to the program:

java -jar MyApp.jar code java 

If the argument contains space, enclose it in double quotes like this:

java -jar MyApp.jar "code java" 2013 

 

3. Specify splash screen

For Swing-based application, we can use the -splash:imagePath flag to show a splash screen at program’s startup. For example:

java -splash:SplashScreen.png MyProgram

 Here the image SplashScreen.png is loaded as splash screen at startup.

 

4. Set system properties

We can use the -Dproperty=value option to specify a system property when running a program:

  • Specify a single property:
java -Dupload.dir=D:\Uploads MyProgram

 if the property’s value contains spaces, enclose it in double quotes:

java -Dupload.dir="D:\My Uploads" MyProgram
  • Specify multiple properties:
java -Dupload.dir=D:\Uploads -Ddownload.dir=D:\Downloads MyProgram 
  • Override predefined property:

We can override the predefined system properties. For example, the following command overrides the system property java.io.tmpdir:

java -Djava.io.tmpdir=E:\Temp MyProgram

 

5. Specify memory size

When launching a Java program, we can specify initial size and maximum size of the heap memory:

    • -Xms<size>: specifies initial heap size
    • -Xmx<size>: specifies maximum heap size.

The size is measured in bytes. It must be multiple of 1024 and is greater than 1MB for initial size and 2MB for maximum size. Append k or K to indicate kilobytes; m or M to indicate megabytes. For example, the following command launches a program with initial heap size 32MB and maximum heap size 1024MB:

java -Xms32M -Xmx1024M MyProgram

 

Other Java Tools Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)ToolsWed, 30 Jan 2013 10:45:51 -0600
How to compile, package and run a Java program using command-line tools (javac, jar and java)https://codejava.net/java-core/tools/how-to-compile-package-and-run-a-java-program-using-command-line-tools-javac-jar-and-javahttps://codejava.net/java-core/tools/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

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:

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)
  • 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:

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:

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:

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

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:

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.

Next, let study about Java classes and objects.

 

Other Java Tools Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)ToolsTue, 19 Jul 2016 01:54:15 -0500
Java serialver command exampleshttps://codejava.net/java-core/tools/using-serialver-command-exampleshttps://codejava.net/java-core/tools/using-serialver-command-examples

The serialver is a tool that comes with JDK. It is used to get serialVersionUID numbers of one or more Java classes. Basically, a serializable class must declare a constant named serialVersionUID (either explicitly by the programmer or implicitly by the compiler) like this:

public class User implements Serializable {

	private static final long serialVersionUID = 1234L;
	
}

The serialVersionUID number is important when dealing with the serialization/de-serialization of objects of a class. The serialver command is helpful in case we want to know that number without having source code of the class. Its syntax is as simple as follows:

serialver [-classpath classpath] [-show] [classname...]

The -classpath option specifies where to look for the classes (in directories or jar files, separated by semicolon marks ;). The -show option displays a simple user interface that allows the user to enter a full class name and then press Enter key or click Show button to display the serialVersionUID number.

Now, let’s see some examples.

  • Displaying serialVersionUID of a class in default package:

    Command:

    serialver ProgressBarDemo

    Output:

    ProgressBarDemo:    static final long serialVersionUID = 8449967402779341329L;

    If the specified class is not serializable, then this message is displayed:

    Class ProgressBarDemo is not Serializable.
  • Displaying serialVersionUID of a class in a specific package:

    The following command displays the serialVersionUID of the class SwingEmailSender under the package net.codejava.mail, assuming that the classes are in the build\classes directory:

    serialver -classpath build\classes net.codejava.mail.SwingEmailSender

    Output:

    net.codejava.mail.SwingEmailSender:    static final long serialVersionUID = -2279575288884790698L;

     

  • Displaying serialVersionUID numbers of two classes:

    Command:

    serialver CustomPanel TestSwingZoom

    Output:

    CustomPanel:    static final long serialVersionUID = 6858515184837974475L;
    TestSwingZoom:    static final long serialVersionUID = 4136458911881435009L;

     

  • Displaying serialVersionUID of a class inside a jar file:

    Command:

    serialver -classpath EmailSender.jar net.codejava.swing.JFilePicker

    Output:

    net.codejava.swing.JFilePicker:    static final long serialVersionUID = -6241197264668893626L;

     

  • Displaying serialVersionUID of two classes inside two jar files:

    Command:

    serialver -classpath SwingAudio.jar;SwingUpload.jar net.codejava.AudioPlayer net.codejava.FileUpload

    Output:

    net.codejava.AudioPlayer:    static final long serialVersionUID = 5499535881565379674L;
    net.codejava.FileUpload:    static final long serialVersionUID = 6409440265121275085L;

     

  • Showing the user interface:

    Command:

    serialver -classpath EmailSender.jar -show

    The Serial Version Inspector window gets displayed, enter the full class name and click the Show button to display the serial version:
    Serial Version Inspector

 

References:

 

Java Serialization Tutorials:

 

Other Java Tools Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)ToolsFri, 06 Dec 2013 07:48:34 -0600
Understanding javac, java and jar tools in JDKhttps://codejava.net/java-core/tools/understanding-the-triad-tools-javac-java-and-jar-in-jdkhttps://codejava.net/java-core/tools/understanding-the-triad-tools-javac-java-and-jar-in-jdk

In the Java Development Kit (JDK), there are three tools which can be used in conjunction to develop Java applications. They are:

  • Java compiler: javac
  • Java application launcher: java
  • Java archive tool: jar

This article gives you an overview about these 3 key tools in Java development.

 

1. Java compiler and Java application launcher

When you are using an editor or an IDE (Integrated Development Environment) like Sublime or NetBeans to develop Java applications, the editor/IDE invokes the java compiler (javac.exe) to compile the source files (.java) and calls the Java launcher (java.exe) to run the compiled files (.class). The following picture illustrates this process:

compile process

You can imagine that the javac and java are two engines of an airplane. Without engines, the airplane cannot take off. Missing one, the airplane cannot flight properly.

Technically, javac is the program that translates Java code into bytecode (.class file) - an intermediate format which is understandable by the Java Virtual Machine (JVM).

And java is the program that starts the JVM, which in turn, loads the .class file, verifies the bytecode and executes it.

javac and java are the cornerstones of the Java programming language. All editors or IDEs rely on these tools for compiling and executing Java applications.

So, how to get started?

It’s very easy. Here are the typical steps to compile and run a Java program whose source file is HelloWorld.java:

  • Compile: javac HelloWorld.java
  • Run: java HelloWorld

Of course there are parameters and options which you can find by typing javac -help or java -help.

Here are the official documentations for these tools:

Certainly it takes time and effort to control these tools. You cannot master them in just 1 or 2 days. Like a pilot has to experience thousands hours of flight in order to completely control the airplane.

Good news is that you can go faster with my experiences compiled into the following articles with practical examples:

 

2. The Java archive tool

Besides javac and java, there’s another one in JDK which is also an important tool in Java programming. It is the Java Archive tool - hence the jar name for its executable file.

Typically, jar is one of the tools that participate in the process of building a Java application, as shown in the following picture:

java process

jar is a command-line tool just like javac and java. This tool is used for putting a group of related .class files into a single unit for easy deployment and execution. The result is a file created with .jar extension. The .jar file is actually a Zip file that contains all the .class files.

Therefore, Java applications and libraries are packed in .jar files, e.g. junit.jar, log4.jar, MyProgram.jar, etc.

You can think that a jar file is the executable of a Java application, like the .exe files on Windows and .sh files on Linux. When you double click the jar file, the operating system is triggered to start the JVM. In turn, the JVM loads and runs the application bundled in that jar file.

As a Java programmer, you need to understand and be able to use the jar tool for packaging your compiled code (.class files) to make deployments of Java libraries and applications in jar files.

For example, suppose that you did write a painter program in Java. It consists of 3 classes:

Painter.java, Shape.java, and Canvas.java

Using the javac tool, you compile these .java files into the following .class files:

Painter.class, Shape.class and Canvas.class

Then type the following command to put all these .class files into a single file named Painter.jar:

jar cf Painter.jar Painter.class Shape.class Canvas.class

The result is a jar file created: Painter.jar

The following picture illustrates the content of this jar file:

jar file

Now, you can execute this Java application using the java command with the -jar option:

java -jar Painter.jar

Type jar -help to see all available options for this tool.

For full syntax description, check the following official documentation from Oracle:

http://docs.oracle.com/javase/8/docs/technotes/tools/windows/jar.html

Over the years, I compile my experiences with this tool in the following article:

Java jar command examples

You can find useful and practical examples about using the jartool in this article.

Here are some key points regarding the Java archive tool:

  • Java libraries and applications are packed in jar files.
  • A jar file is actually a Zip file. That means you can use any archive tools such as WinZip, WinRar, 7-Zip,… to view and extract content of a jar file.
  • The jar tool provided by JDK is a command-line program that allows us to create, view and extract jar files.
  • You can use the jar tool to extract a zip file or compress a file to zip format.

 

3. Conclusion

When you are working with the editor or IDE, they do all the interactions with javac, java and jar to hide the complex details and increase productivity.

That’s good! You can build Java applications without manually touching these tools. However, from my experience, I recommend you to study and play with these tools because of the following benefits:

  • You understand the nuts and bolts of Java, which gives you experiences to solve problems related to compilation and execution of Java programs.
  • You equip yourself with skills of working with or without IDEs. Sometimes, working directly with javac, java and jar saves you a lot of time than using an IDE, hence increasing your productivity.
  • You have more control over Java programming, e.g. you can easily work with various tools that rely on javac, java and jar such as Ant, Maven, Gradle, etc.

My friend, today I want to tell you this: to master Java programming, you have to master its core: the Java compiler, Java launcher and Java archive tools. If you want to fly the airplane, you must be able to control the engines.

 

Other Java Tools Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)ToolsMon, 13 Jul 2015 10:33:15 -0500
Java Shell (jshell) Tutorialhttps://codejava.net/java-core/tools/java-9-the-java-shell-jshell-tutorialhttps://codejava.net/java-core/tools/java-9-the-java-shell-jshell-tutorial

The Java Shell or jshell is an interactive command-line tool that allows programmers to rapidly learn, investigate and explore the Java programming language and its API. One can type any valid Java code into the console and get immediate results and feedback, without the need to write a verbose class with a main method. Thus using jshell is more efficient than edit/compile/execute and System.out.println approach.

Imagine when you want to test an API, you can open jshell, type the code and get results immediately. No need to write a class, then a main method, then compile and run the program.

In this tutorial, we’re going to help you understand and get the most out of jshell, for your daily Java learning.

 

1. Start jshell

The Java Shell comes with JDK 9 so you need to have JDK 9 installed on your computer. If the PATH environment variable is configured properly, you can type jshell anywhere in the command line prompt:

jshell

Otherwise you can go to JDK’s installation directory, go in the bin folder and open the jshell program, for example (on Windows):

c:\Program Files (x86)\Java\jdk-9\bin>jshell

Then you see a welcome message and the command prompt changes to jshell>:

start jshell

Type:

/help intro

To see introduction information about jshell:

help intro jshell

Pay attention to this statement:

These little chunks of Java code are called 'snippets'.

That means what you type is called snippets and these snippets are given identifiers (ID) so you can edit or drop them later on.

Now you’re in the Java Shell. Read the next sections to see how to use it.

 

2. Execute Java Expressions and Statements

Basically, you can type any valid expressions and statements in the Java language, the shell gives you results immediately, for example:

jshell> 123 + 456
$1 ==> 579

This evaluates the expression ‘123 + 456’ and gives the result: 579. The result is stored in a variable named $1.

Similarly, you can concatenate two String literals like this:

jshell> "Java " + "World"
$2 ==> "Java World"

And the result is assigned to a new variable named $2, implicitly.

You can test the substring() method on a String literal like this:

jshell> "Java World".substring(0, 4)
$3 ==> "Java"

You see, the result String is stored in a variable named $3, implicitly. You can declare a variable just like normal Java code:

jshell> List<String> list = new ArrayList<>()
list ==> []

This creates a new ArrayList collection, and the feedback tells us that the list is initially empty.

The shell can remember all variables you declared, so you can add elements to the above list like this:

jshell> list.add("Apple")
$5 ==> true

jshell> list.add("Banana")
$6 ==> true

jshell> list.add("Something")
$7 ==> true

And simply type the variable name to see its value:

jshell> list
list ==> [Apple, Banana, Something]

Here, the elements in the list collection are printed out. Now you can investigate other methods of the List interface (the declared type of the variable list), for example:

jshell> list.size()
$9 ==> 3

jshell> list.get(2)
$10 ==> "Something"

jshell> list.get(5)
|  java.lang.IndexOutOfBoundsException thrown: Index 5 out-of-bounds for length 3
|        at Preconditions.outOfBounds (Preconditions.java:64)
|        at Preconditions.outOfBoundsCheckIndex (Preconditions.java:70)
|        at Preconditions.checkIndex (Preconditions.java:248)
|        at Objects.checkIndex (Objects.java:372)
|        at ArrayList.get (ArrayList.java:439)
|        at (#11:1)

jshell> list.remove(2)
$12 ==> "Something"

jshell> list
list ==> [Apple, Banana]

You can see the statement list.get(5) throws an exception because the list contains only 3 elements. Very useful and rapid to learn Java programming with jshell, right?

At anytime, you can type /varsto list all the declared variables and their values. For example:

jshell> /vars
|    int $1 = 579
|    String $2 = "Java World"
|    String $3 = "Java"
|    List<String> list = [Apple, Banana]
|    boolean $5 = true
|    boolean $6 = true
|    boolean $7 = true
|    int $9 = 3
|    String $10 = "Something"
|    String $11 = null
|    String $12 = "Something"

 

3. Declare a Java Method

The Java Shell allows to declare a method without writing any enclosing class and invoke the method later. For example:

jshell> public double triangleSquare(int base, int height) {
   ...> return 0.5 * base * height;
   ...> }
|  created method triangleSquare(int,int)

Press Enter after each line and the shell can automatically detect when a method completes.

This declares a method that calculates the area of a triangle given its base and height. Then you can invoke the method directly without creating a new instance of a class:

jshell> triangleSquare(5, 8)
$15 ==> 20.0

You see? This is very convenient to test a method rapidly.

And you can type/methods command to see all the declared methods. For example:

jshell> /methods
|    double triangleSquare(int,int)

If you want to redefine the method, simply type the method declaration again (use the Up/Down arrow keys to reuse previous inputs). You will see the feedback ‘modified method…’ - something like this:

|  modified method triangleSquare(int,int)

 

4. Declare a Java Class

Similarly to method declaration, you can declare a class by typing its code just like you write Java code in an editor, and the shell can detect when the class completes. For example:

jshell> class Person {
   ...>     String name;
   ...>     int age;
   ...>
   ...>     public void say() {
   ...>        System.out.println("Hello, my name is: " + name);
   ...>     }
   ...> }
|  created class Person

Then you can test the class like this:

jshell> Person p = new Person()
p ==> Person@10587f1

jshell> p.name = "John"
$18 ==> "John"

jshell> p.age = 33
$19 ==> 33

jshell> p.say()
Hello, my name is: John

To see all the declared classes, type /types command in the shell. For example:

jshell> /types
|    class Person

If you want to redefine the class, simply type the class declaration again (use the Up/Down arrow keys to reuse previous inputs). You will see the feedback ‘modified class…’ - something like this:

|  modified class Person

 

5. Declare a Java Interface

Similar to class declaration, you can declare an interface and the shell can detect when the declaration completes. Here’s an example:

jshell> public interface Animal {
   ...>      public void move();
   ...>      public void eat();
   ...>      public void sleep();
   ...> }
|  created interface Animal

Here, we declare the interface Animal with three methods. Now try to create a class that implements this interface like this:

jshell> class Dog implements Animal {
   ...> }
|  Error:
|  Dog is not abstract and does not override abstract method sleep() in Animal
|  class Dog implements Animal {
|  ^----------------------------...

We got an error saying that the Dog class doesn’t override the abstract methods defined by the Animal interface. Very useful for learning the Java language, right?

The declared interfaces also listed when typing the /types command:

jshell> /types
|    class Person
|    interface Animal

You can redefine the interface by retyping its declaration (using Up/Down arrow keys to reuse previous inputs). You can see the feedback ‘replaced interface…’ - something like this:

|  replaced interface Animal

 

6. Using Java Imports

By default, jshell imports some common packages on startup. You can type /importscommand to see all the available imports:

jshell> /imports
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*

Note that though the java.lang package is not listed here, it is also imported by default.

The following example shows two packages java.util.nio and java.sql:

jshell> import java.nio.*;
jshell> import java.sql.*;

or import a specific type:

jshell> import java.sql.Connection

Type /imports command again and you will see the recent import statements are listed:

jshell> /imports
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*
|    import java.nio.*
|    import java.sql.*
|    import java.sql.Connection

  

7. View History

You can view the history of what you typed since the shell was launched, using the /history command. For example:

jshell> /history

123 + 456
"Java " + "World"
"Java World".substring(0, 4)
List<String> list = new ArrayList<>()
list.add("Apple")
list.add("Banana")
list.add("Something")
list.siz()
list.size()
list.get(5)
list.remove(2)
list
/vars
public double triangleSquare(int base, int height) {
return 0.5 * base * height;
}
triangleSquare(5, 8)
/methods
/imports

The history is stored in the current session only. If you quit the shell, the history is cleared.

 

8. Use Tab Completion

One interesting and helpful feature of jshell is code auto completion and API documentation. When entering code in the shell, you can use the Tab key to automatically complete an item, or show a list of possible options.

For example, if there’s a method named triangleSquare(), you can just type the triangle and press the Tab key, the shell automatically completes the method name:

jshell> /methods
|    double triangleSquare(int,int)

jshell> triangle (Press Tab key)

Then the shell automatically completes the method name:

jshell> triangleSquare(
triangleSquare(

jshell> triangleSquare(

You can also use the Tab key to show different signatures of methods or constructors, along with their documentation.

For example, enter the following declaration:

jshell> List<String> items = new ArrayList<>(

When typed the open parenthesis, press the Tab key and the shell shows a list of signatures of constructors of the ArrayList class:

jshell> List<String> items = new ArrayList<>(
$8      list    names

Signatures:
ArrayList<E>(int initialCapacity)
ArrayList<E>()
ArrayList<E>(Collection<? extends E> c)

<press tab again to see documentation>

jshell> List<String> items = new ArrayList<>(

Now, press the Tab key you will see the documentation of the first signature:

jshell> List<String> items = new ArrayList<>(
ArrayList<E>(int initialCapacity)
Constructs an empty list with the specified initial capacity.

Parameters:
initialCapacity - the initial capacity of the list

Thrown Exceptions:
IllegalArgumentException - if the specified initial capacity is negative

<press tab to see next documentation>

jshell> List<String> items = new ArrayList<>(

It’s very useful, isn’t it? Press the Tab key again you will the documentation of the next signature, and so on.

 

9. List the code snippets you have typed

If you want to review all the code snippets you have typed, type /list command. For example:

jshell> /list

   1 : public double triangleSquare(int base, int height) {
       return 0.5 * base * height;
       }
   2 : triangleSquare(5, 8)
   3 : class Person {
       String name;
       int age;
       public void say() {
       System.out.println("Hello, my name is: " + name);
       }
       }
   4 : Person p = new Person();
   5 : p.name = "John"
   6 : p.age = 33
   7 : p.say()
   8 : List<String> list = new ArrayList<>();
   9 : list.add("Apple")
  10 : list.add("Banana")
  11 : list.add("Something")

Note that there are numbers on the right act as snippet IDs, so you can use these IDs for further operations. For example, the following command shows only source code of the Person class (the code snippet of this class has ID 3 as shown above):

jshell> /list 3

   3 : class Person {
       String name;
       int age;
       public void say() {
       System.out.println("Hello, my name is: " + name);
       }
       }

The /list <id> command allows you to list the snippet with the specified snippet ID.

You can also use the /list <name> command to list the code of the given item name. For example, the following command shows the code of the Person class:

/list Person

 

10. Drop a Snippet

You can drop a snippet you have typed by using the command /drop <name> or /drop <id>. <name> can be variable name, method name or class name; and <id> is the ID of the snippet you see using the /list command.

For example, the following command removes the declaration of the Person class:

jshell> /drop Person
|  dropped class Person

That means you can no longer use the Person class and any reference variables of this class.

Suppose the /list command shows the following snippets:

jshell> /list

   2 : triangleSquare(5, 8)
   4 : Person p = new Person();
   5 : p.name = "John"
   6 : p.age = 33
   7 : p.say()
   8 : List<String> list = new ArrayList<>();
   9 : list.add("Apple")
  10 : list.add("Banana")
  11 : list.add("Something")

Then you can use the command /drop 8 or /drop listto remove the declaration of the variable list:

jshell> /drop 8
|  dropped variable list

 

11. Edit a code snippet in an external editor

You can use the command /edit <id> to edit a code snippet with the specified snippet ID in an external editor. For example, to edit the snippet of the Person class (snippet ID = 3):

jshell> /edit 3

Then jshell opens an external editor looks like this:

external editor

Very cool, right? Now you can edit the code easily, then click Accept and Exit. For example:

external editor - edited

The shell gives a feedback:

jshell> /edit 3
|  modified class Person

You can use the /list command to see the updated code:

jshell> /list

   1 : public double triangleSquare(int base, int height) {
       return 0.5 * base * height;
       }
   2 : triangleSquare(5, 8)
   4 : Person p = new Person();
   5 : p.name = "John"
   6 : p.age = 33
   7 : p.say()
   8 : List<String> list = new ArrayList<>();
   9 : list.add("Apple")
  10 : list.add("Banana")
  11 : list.add("Something")
  12 : class Person {
           String name = "";
           int age = 18;

           public void say() {
               System.out.println("Hello, my name is: " + name);
           }
       }

But now, the snippet ID of the updated code has changed.

Note that you can also use the /edit <name> command to edit a code snippet. For example, the following command edits code of the Person class:

/edit Person

 

12. Open a Source File

The Java Shell provides the /open <filename> command that allows you to open a file and read its contents and snippets and command, which is very useful for reusing commands or code. The file can contains any Java code and valid jshell’s commands.

For example, the following command imports the code in Person.java file to the shell:

jshell> /open E:\Java\Person.java

You can also use the /open command with some predefined scripts:

/open DEFAULT: loads the default imports.

/open JAVASE: imports all JavaSE packages.

/open PRINTING: uses print, println and printf methods as jshell methods.

 

13. Save Snippets to a File

You can save the snippets or commands you have typed to a specified file, using the following command:

/save <file>

For example, the following command saves snippets and commands to a file named snippets.txt in E:\Java directory:

/save E:\Java\snippets.txt

Type the command /help save to see additional options for the /save command.

 

14. Using Help

Type /help to list all the commands supported by jshell.

And type /help <command>to see the usage of a specific command, for example:

jshell> /help /history
|
|  /history
|
|  Display the history of snippet and command input since this jshell was launched.

You can also use the ? as shortcut for help, for example:

/? /history

 

15. Use Startup Options

You can specify options when launching jshell, for examples:

- loading scripts from files

- specify directories and JAR files in classpath

- send flags to the compiler and runtime system

- set feedback mode (normal, verbose or concise)

...etc

See the options details in jshell Tool Reference.

 

16. Exit jshell

Type /exit to end the session and quit the shell:

jshell> /exit
|  Goodbye

c:\Program Files (x86)\Java\jdk-9\bin>

For more information about using the Java Shell, refer to the following documents:

 

References:

 

Other Java Tools Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)ToolsSun, 17 Sep 2017 23:02:02 -0500
Run a Java program directly from source code filehttps://codejava.net/java-core/tools/run-a-java-program-directly-from-source-code-filehttps://codejava.net/java-core/tools/run-a-java-program-directly-from-source-code-file

Perhaps you’re very familiar with the traditional way of compiling and running Java program in command line as follows:

javac Hello.java

java Hello

This involves in 2 steps: compile the .java file to the byte code .class file, and run the compiled .class file. It is somewhat verbose and “ceremony” for small, utility programs that are contained in a single source code file.

So from JDK 11, there’s a simpler way which you can use to run a Java program directly from its source file, like this:

java Hello.java

This feature is called Launch Single-File Source-Code Programs available in JDK since Java 14. Use the same command if the source file has package statement.

Under the hood, the Java compiler is invoked to compile the source file in memory, and then the Java Virtual Machine executes the compiled code. That means the process is the same as in previous JDK versions – It’s not interpreted.

Of course you can pass arguments to the program as normal. For example:

java Sum.java 10 38 29

And pass JVM arguments as normal. For example:

java –cp mysql-connector-java.jar Database.java

Note that this feature only applies for a program contained in a single source code file and no .class files generated. I think it will make learning Java programming more easily and more convenient for running small, utility programs.

Watch the video:

https://www.youtube.com/watch?v=U7Rp9hq0_Zk

 

Other Java Tools Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)ToolsFri, 03 Apr 2020 19:33:43 -0500