[Java] javac, jar, java command cheat sheet

1 minute read

The order from the creation of a program in Java to the execution.

  1. compile. Use the javac command.
  2. Create a jar file. Use the jar command.
  3. run. Use the java command.

javac command

help

javac --help

The same applies to javac -help and javac -? .
javac -h is different.

compile Java8 or earlier module not used

compile-java8-earlier-none-module.sh


javac -d /path/to/bin/directory \
--class-path /path/to/files1:/path/to/files2 \
--release 8 \
$(find /path/to/src/directory -name "*.java")

Select version with --release.
Compile all * .java in the specified directory with $ (find / path / to / src / directory -name "* .java") .

compile Java9 or later module use

compile-java9-later-with-module.sh


javac -d /path/to/bin/directory \
--module-path /path/to/module/dir1:/path/to/module/dir2 \
--release 11 \
$(find /path/to/src/directory -name "*.java")

jar command

help

jar --help

The same applies to jar -? and jar -h.

create

jar-create-simple.sh


jar -c \
-f /path/to/Export.jar \
-C /path/to/src/directory .

When using -C, don’t forget the . at the end.

create Executable-jar

jar-create-executable.sh


jar -c \
-f /path/to/Executable.jar \
-e package.to.MainClass \
-C /path/to/src/directory .

Specify the entry point with -e.

java command

help

java --help

run

run.sh


java -cp /path/to/file1:/path/to/file2 \
package.to.MainClass

run Executable-jar

run-executable-jar.sh


java -cp /path/to/file1:/path/to/file2 \
-jar /path/to/Executable.jar

run Java9 or later module use

run-with-module.sh


java --module-path /path/to/module/dir1:/path/to/module/dir2 \
--module name.of.module/package.to.MainClass

build and run sample

build and run Java8 or earlier module not used

build-and-run-none-module.sh


#!/bin/sh

path_src="/path/to/src/directory"
path_bin="/path/to/bin/directory"
path_export_jar="/path/to/Export.jar"
path_lib="/path/to/lib/*"
entry_point="package.to.MainClass"
version="8"

# compile
javac -d ${path_bin} \
--class-path ${path_lib} \
--release ${version} \
$(find ${path_src} -name "*.java")

# jar
jar -c \
-f ${path_export_jar} \
-C ${path_bin} .

# run
java -cp ${path_lib}:${path_export_jar} \
${entry_point}

build and run Java9 or later module use

build-and-run-with-module.sh


#!/bin/sh

path_src="/path/to/src/directory"
path_bin="/path/to/bin/directory"
path_export_jar="/path/to/Export.jar"
path_lib="/path/to/lib"
entry_point="name.of.module/package.to.MainClass"
version="11"

# compile
javac -d ${path_bin} \
--module-path ${path_lib} \
--release ${version} \
$(find ${path_src} -name "*.java")

# jar
jar -c \
-f ${path_export_jar} \
-C ${path_bin} .

# run
java --module-path ${path_lib}:${path_export_jar} \
--module ${entry_point}

Tags:

Updated: