You can only call the main method. Design your main method such that it calls the method you want.

When I say call main method, you don't explicitly invoke it. It's the only entry point to a java program when you invoke it.

If your class looks like:

package com.foo;

public class Test {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You can use the following command line to invoke the main from within the directory where you can find com/foo/Test.class (If you're in the classes directory in the structure shown far below):

java com.foo.Test

If you want to do so from a different (See the directory structure far below) directory, then you'll have to set classpath.

java -cp /path/to/classes com.foo.Test

Assume the below directory structure for clarity.

-path
    -to
        -classes
            -com
                -foo
                    >Test.class
Answer from adarshr on Stack Overflow
Top answer
1 of 4
17

You can only call the main method. Design your main method such that it calls the method you want.

When I say call main method, you don't explicitly invoke it. It's the only entry point to a java program when you invoke it.

If your class looks like:

package com.foo;

public class Test {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You can use the following command line to invoke the main from within the directory where you can find com/foo/Test.class (If you're in the classes directory in the structure shown far below):

java com.foo.Test

If you want to do so from a different (See the directory structure far below) directory, then you'll have to set classpath.

java -cp /path/to/classes com.foo.Test

Assume the below directory structure for clarity.

-path
    -to
        -classes
            -com
                -foo
                    >Test.class
2 of 4
3

You can't execute an arbitrary method directly from a shell script, you'll need to have that method exposed externally in some way.

The simplest way of course is to write a main method that directly invokes the code you want to test.

Alternatively, you could make use of a Java application that takes parameters to act as a sort of launcher. In its crudest form you can imagine an app that takes a classname and method name as arguments, then instantiates the class and invokes the method via reflection. In a similar vein, but a bit more elegant, we use an app that invokes operations exposed via JMX in order to fire certain methods on a server when required.

Ultimately though, bash (or equivalent) doesn't understand JVM bytecode. You will need to launch a Java process to run the method, which will involve executing some main method that in turn invokes what you need.

๐ŸŒ
Spiceworks
community.spiceworks.com โ€บ programming & development
How to Call Java Program in Shell Script? - Programming & Development - Spiceworks Community
November 19, 2008 - I wrote a Java program to say โ€œhello.javaโ€ which contains a main method. How can I call this in a shell script?
๐ŸŒ
Stack Exchange
unix.stackexchange.com โ€บ questions โ€บ 237104 โ€บ how-to-run-java-program-in-bash-script-and-give-it-one-argument
directory - How to run Java program in Bash script and give it one argument? - Unix & Linux Stack Exchange
October 19, 2015 - I know about that Java thingy., in fact, it's not about Java - but how to make the OS, run a program, in a way that I want, with all requirements supplied. ... There is Caja-actions Configration tool to add the open with ABC in context menu. There is command tab in Caja Action tool, there you can provide the script path and the directory argument.
๐ŸŒ
Unix.com
unix.com โ€บ shell programming and scripting
How to call Java by using shell script - Shell Programming and Scripting - Unix Linux Community
November 19, 2017 - Hi All, I am new to shell script, just wanted you guy to help. How do i call a java program by using shell script, pls give some samle code for it, thank you ver much.
Top answer
1 of 4
3

I don't know anything about Java, but I can show you a proof of concept. Say we have localfile.txt:

Here is the local file.

and on the remote machine, we have remote.sh:

#!/bin/bash
cat /dev/stdin

Note that the script on the remote machine invokes a program which reads from stdin. Then pass the contents of localfile.txt to your ssh command:

user@local:~$ cat localfile.txt | ssh user@remote remote.sh
Here is the local file.

Your Java program is trying to read a file which does not exist on the remote machine. I guess you could try to mimic a local file.

Change remote.sh to:

#!/bin/bash
cat "$@"

and invoke it with

user@local:~$ cat localfile.txt | ssh user@remote 'remote.sh <(cat /dev/stdin)'
Here is the local file.

I think it would be easier to change that part in your Java program to read from stdin.

I guess things might get messy if localfile.txt contains anything that might be interpreted by the shell as expandable (such as *), but that's for you to figure out.

2 of 4
2

The problem is that the shell redirection (<) sends the file over the ssh tunnel. And the Java class is expecting not the file, but a string with the "filename" of a local file that will be read with a FileReader.

Instead of passing the filename to the FileReader, read from the standard input.

InputStreamReader isReader = new InputStreamReader(System.in);
BufferedReader iR  = new BufferedReader (isReader);

Used this as a reference: https://stackoverflow.com/questions/5724646/how-to-pipe-input-to-java-program-with-bash

Now your class will be:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;

public class ReadFirstLine 
{
    public static void main(String[] args) throws Exception 
    {
       String filename = args[0];
       System.out.println(filename);

       //BufferedReader iR  = new BufferedReader (new FileReader(filename));
       InputStreamReader isReader = new InputStreamReader(System.in);
       BufferedReader iR  = new BufferedReader (isReader);

       BufferedWriter oW = new BufferedWriter(new OutputStreamWriter(System.out));

       //outputWriter.write(iR.readLine());
       System.out.println(iR.readLine());

       iR.close();
       oW.close();
    }
}

But for this task I would definitely use instead:

head -1 filename.txt

:)

Find elsewhere
๐ŸŒ
Kevin Boone
kevinboone.me โ€บ exec.html
How to run a shell script from a Java application - Kevin Boone
Running a shell script from a Java program using Runtime.exec() appears simple. In practice, there are many pitfalls. This article describes how to avoid at least some of them.
๐ŸŒ
Netjstech
netjstech.com โ€บ 2016 โ€บ 10 โ€บ how-to-run-shell-script-from-java-program.html
How to Run a Shell Script From Java Program | Tech Tutorials
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RunningSS { public static void main(String[] args) { Process p; try { String[] cmd = { "sh", "/home/adb/Documents/test.sh"}; p = Runtime.getRuntime().exec(cmd); p.waitFor(); BufferedReader reader=new BufferedReader(new InputStreamReader( p.getInputStream())); String line; while((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } After executing this Java program with the given shell script, if you verify at the location where your Java program is you will see a directory test created and a file SAMPLE with in that directory.
๐ŸŒ
Adam-bien
adam-bien.com โ€บ roller โ€บ abien โ€บ entry โ€บ run_java_source_as_shell
Run Java Source as Shell Scripts
To execute the main method you will have to declare a specific shebang first (#!/[PATH]/bin/java --source [VERSION]), then a java class with a main method: #!/usr/bin/java --source 11 public class App{ public static void main(String ...args){ System.out.println("hello, java (like script)"); } }
๐ŸŒ
Quora
quora.com โ€บ How-do-I-run-a-shell-script-from-Java-code
How to run a shell script from Java code - Quora
Answer (1 of 7): Here are multiple ways already suggested in stackoverflow and both are good: How to run Unix shell script from java code? Run shell script from Java Synchronously
๐ŸŒ
Quora
quora.com โ€บ Is-there-any-way-to-call-Java-methods-from-shell-scripts
Is there any way to call Java methods from shell scripts? - Quora
Answer (1 of 3): You might want to look up jshell, The jshell tool allows you to execute Java code, getting immediate results. You can enter a Java definition (variable, method, class, etc), like: int x = 8 or a Java expression, like: x + x or a Java statement or import.
๐ŸŒ
Unix.com
unix.com โ€บ shell programming and scripting
Calling Java Method from UNIX using shell script - Shell Programming and Scripting - Unix Linux Community
October 19, 2017 - Hi All, I need to call a java method from a shell script. I know we can use the command java ClassName to call the main method in it. But I need to call another method that is there in the class and pass an email to โ€ฆ
๐ŸŒ
Quora
quora.com โ€บ How-do-I-write-a-bash-script-to-run-a-Java-program-with-a-series-of-arguments-automatically
How to write a bash script to run a Java program with a series of arguments, automatically - Quora
Answer: Enter the following in a text file using a text editor. Naturally, substitute the name of your program and the accordant arguments. Type it exactly the way you would do it on a shell commandline. Lets say you name it [code ]myProgram.sh[/code] : [code]#! /bin/bash # since this is a java ...
๐ŸŒ
GitHub
gist.github.com โ€บ sangupta โ€บ 9d432f8368811533f99fec44b3ea9428
A simple shell script to run a Java program from Linux shell in the background ยท GitHub
This is a simple script to run a Java program from Linux shell in the background - so that the process does not terminates when you log out of the shell.
๐ŸŒ
Princeton CS
introcs.cs.princeton.edu โ€บ java โ€บ 15inout โ€บ linux-cmd.html
Java and the Linux Shell
You will use the java command to execute your program. From the shell, type the java command below.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 39729320 โ€บ how-to-call-java-method-from-shell-scripts
bash - how to call java method from shell scripts - Stack Overflow
#!/bin/bash JAVA_HOME=/usr/lib/jvm/jdk1.6.0_02 CLASSPATH=/home/freddy/myapp/lib/EffectedUsers.jar: . $JAVA_HOME/bin/java -cp $CLASSPATH EffectedUsers exit 0 ... Re nothing is working try to be more specific on exactly what is the behavior you get, vs what you would expect to get. This will increase the likelihood of someone finding the answer.