user3676943 user3676943 - 3 years ago 272
Java Question

How to run a simple class file from Linux shell?

I am new to Java and I want to run a simple java file on my Linux host.

I started with a simple shell command:

mkdir -p ~/py4j/examples

I put in the above folder

The file looks like this:

// ~/py4j/examples/

package py4j.examples;

import py4j.GatewayServer;

public class AdditionApplication {

public int addition(int first, int second) {
return first + second;

public static void main(String[] args) {
AdditionApplication app = new AdditionApplication();
// app is now the gateway.entry_point
GatewayServer server = new GatewayServer(app);

Notice that it imports this:

import py4j.GatewayServer;

The above import depends on code here:


Next I installed java and set two env variables:

export JAVA_HOME=${HOME}/jdk
export PATH="${JAVA_HOME}/bin:${PATH}"

I use this shell command to see it:

${JAVA_HOME}/bin/java -version

It says:

java version "1.8.0_152"
Java(TM) SE Runtime Environment (build 1.8.0_152-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)

Next I ran two shell commands:

cd ~
javac -cp py4j0.10.6.jar py4j/examples/

The above command created a class file:

dan@h79:~ $ ll py4j/examples/AdditionApplication.*
-rw-rw-r-- 1 dan dan 472 Dec 22 20:59 py4j/examples/AdditionApplication.class
-rw-rw-r-- 1 dan dan 431 Dec 22 20:58 py4j/examples/
dan@h79:~ $

Next I ran another shell command:

dan@h79:~ $ java -cp py4j0.10.6.jar py4j.examples.AdditionApplication
Error: Could not find or load main class py4j.examples.AdditionApplication
dan@h79:~ $

Question: How do I run ~/py4j/examples/AdditionApplication.class ?

Answer Source

You need to add classpath for AdditionApplication as well.

java -cp py4j0.10.6.jar:. py4j.examples.AdditionApplication

Notice the :.. : is path separator, . is current directory. Of course that assumes current folder is ~,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download