Try replacing

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};

with

String[] command = {"/teste/teste_back/script.sh", argument1, argument};

Refer ProcessBuilder for more information.

ProcessBuilder(String... command)

Constructs a process builder with the specified operating system program and arguments.

Answer from Jagan N on Stack Overflow
Top answer
1 of 3
6

Try replacing

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};

with

String[] command = {"/teste/teste_back/script.sh", argument1, argument};

Refer ProcessBuilder for more information.

ProcessBuilder(String... command)

Constructs a process builder with the specified operating system program and arguments.

2 of 3
5

You can define a method with ProcessBuilder.

public static Map execCommand(String... str) {
    Map<Integer, String> map = new HashMap<>();
    ProcessBuilder pb = new ProcessBuilder(str);
    pb.redirectErrorStream(true);
    Process process = null;
    try {
        process = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader reader = null;
    if (process != null) {
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    }

    String line;
    StringBuilder stringBuilder = new StringBuilder();
    try {
        if (reader != null) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        if (process != null) {
            process.waitFor();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if (process != null) {
        map.put(0, String.valueOf(process.exitValue()));
    }

    try {
        map.put(1, stringBuilder.toString());
    } catch (StringIndexOutOfBoundsException e) {
        if (stringBuilder.toString().length() == 0) {
            return map;
        }
    }
    return map;
}

You can call the function to execute shell command or script

String cmds = "ifconfig";
String[] callCmd = {"/bin/bash", "-c", cmds};
System.out.println("exit code:\n" + execCommand(callCmd).get(0).toString());
System.out.println();
System.out.println("command result:\n" + execCommand(callCmd).get(1).toString());
🌐
Revisit Class
revisitclass.com › home › execute the shell commands using processbuilder in java
Execute the shell commands using ProcessBuilder in Java -
December 17, 2021 - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RunCmdPrompt{ public static void main(String[] args) throws IOException, InterruptedException { String cmd = "dir"; ProcessBuilder builder = new ProcessBuilder(); builder.command("cmd.exe","/c",cmd); Process result = builder.start(); int exitcode=result.waitFor(); System.out.println("Exit code: " + exitcode); if (exitcode == 0) { System.out.println("Success!"); } else { System.out.println("Abnormal failure"); System.out.println("Quitting the program"); System.exit(1); } BufferedReader stdInput = new BufferedReader(new InputStreamReader(result.getInputStream())); String output; while ((output = stdInput.readLine()) != null) { System.out.println(output); } } }
🌐
GitHub
gist.github.com › simonwoo › c21811eddf0392034946
execute a shell script from java.md · GitHub
/** * execute shell script */ private static void executeScript() { try { String bash = "/bin/bash"; String script = "script.sh"; String[] command = { bash, script }; System.out.println("Starting execute the script"); ProcessBuilder processBuilder = new ProcessBuilder(command); Map<String, String> env = processBuilder.environment(); env.put("ENV_KEY", "ENV_VALUE"); Process process = processBuilder.start(); // output the process BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } // wait for the end of process process.waitFor(); System.out.println("Script executed successfully"); } catch (Exception e) { throw new RuntimeException("Can not execute the install script successfully"); } } ProcessBuilder is used to create operating system processes.
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - ProcessBuilder processBuilder = new ProcessBuilder(); // -- Linux -- // Run a shell command processBuilder.command("bash", "-c", "ls /home/mkyong/"); // Run a shell script //processBuilder.command("path/to/hello.sh"); // -- Windows -- // Run ...
🌐
Stack Overflow
stackoverflow.com › questions › 33360737 › running-a-shell-script-using-process-builder-in-java
Running a shell script using process builder in java - Stack Overflow
so to make this work, I made another script called command.sh which just has this shell commmand - cat input.txt | shellscript.sh · and i placed them all in the same directories. When i run it, there are no errors but the commands inside the script does not seem to run. public class testing { public static void main(String[] args) throws IOException,InterruptedException { Process p = new ProcessBuilder("/bin/sh", "/Random Files/command.sh").start(); } }
🌐
Javasavvy
javasavvy.com › home › running a shell script using process builder in java
Running shell script using process builder java,shell script execution in java
April 20, 2024 - suppose you want to execute a shell script with attributes like admin,password,url like show in below : ... String cmd= " /home/jay/sam_script.sh admin passwod 127.0.0.1" ; ProcessBuilder pb = new ProcessBuilder(cmd.split(" ")); Process pr = pb.start();
🌐
Coderanch
coderanch.com › t › 459571 › os › ProcessBuilder-executing-shell-script-java
how to use ProcessBuilder for executing a shell script from java? (GNU/Linux forum at Coderanch)
All exceptions are handles in the shell script and it exits properly from shell script. Regards, Acharya ... You can not use redirections with ProcessBuilder, afaik: Instead you have to open System.err and generate ShellscriptError.err yourself. Together with runtime.exec here is a good ...
🌐
Adobe Experience League
experienceleaguecommunities.adobe.com › home › product communities › adobe experience manager › adobe experience manager sites › how to execute a shell script using processbuilder from sling servlet
How to execute a shell script using ProcessBuilder from Sling Servlet | Community
October 21, 2016 - If you observe closely PWD=/mnt/crx/author is the path where AEM internal process is looking at, USR=crx is the User that AEM is using internally to run the code. So i copied my "shell script" to "/mnt/crx/author" and also gave execute permission to user "crx".
🌐
Wordpress
singztechmusings.wordpress.com › 2011 › 06 › 21 › getting-started-with-javas-processbuilder-a-sample-utility-class-to-interact-with-linux-from-java-program
Getting started with Java’s ProcessBuilder: A simple utility class to interact with Linux from Java program |
June 23, 2011 - i need to pass arguments to the shell script as below · params = java.util.Arrays.asList(“./app/bin/testRunner.sh” “-n1” “-lTestScript” “-f./reports/snbc/”); ProcessBuilder processBuilder = new ProcessBuilder(params);
Find elsewhere
Top answer
1 of 1
8

"(actually it's "ls" but it should work exactly the same way)"

No, it is not. Because the 'ls' process returns immediately after its call. Your omixplayer at the other hand is interactive and will accept commands at runtime.

What you have to do:

  • create a class which implements Runnable and let this class read from the prs.getInputStream(). You will need this because the .read() will block and wait for new data to read.

  • get the OutputStream of the Process object (prs.getOutputStream()). Everything you write to the OutputStream will be read from your omixplayer. Don't forget to flush the OutputStream and every command needs an "\n" at the end to be executed.

Like that:

public class TestMain {
    public static void main(String a[]) throws InterruptedException {

        List<String> commands = new ArrayList<String>();
        commands.add("telnet");
        commands.add("www.google.com");
        commands.add("80");
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.redirectErrorStream(true);
        try {

            Process prs = pb.start();
            Thread inThread = new Thread(new In(prs.getInputStream()));
            inThread.start();
            Thread.sleep(2000);
            OutputStream writeTo = prs.getOutputStream();
            writeTo.write("oops\n".getBytes());
            writeTo.flush();
            writeTo.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class In implements Runnable {
    private InputStream is;

    public In(InputStream is) {
        this.is = is;
    }

    @Override
    public void run() {
        byte[] b = new byte[1024];
        int size = 0;
        try {
            while ((size = is.read(b)) != -1) {
                System.err.println(new String(b));
            }
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

P.S.: Keep in mind this example is quick an dirty.

🌐
To The New
tothenew.com › home › executing linux shell command using processbuilder
Executing linux shell command using ProcessBuilder | TO THE NEW Blog
December 19, 2016 - [java]ProcessBuilder pb = new ProcessBuilder("convert", "-adaptive-resize", "${width}x${height}!", sourceFilePath, destinationFilePath); Process p = pb.start() p.waitFor() [/java] It works seemlessly!!!
🌐
Softorks
softorks.com › en › java › how-to-execute-shell-command-java-macos-processBuilder.php
Java - Execute Shell Command Using ProcessBuilder - MacOs
August 20, 2019 - import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; public class ExecuteShellComandProcessBuilder { public static void main (String [] args) throws IOException, InterruptedException{ String [] command = {"ping", "google.com"}; ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(System.getProperty("user.home"))); try { Process process = processBuilder.start(); BufferedReader reader = new BufferedReader (new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } int exitCode = process.waitFor(); System.out.println ("\nExited with error code : " + exitCode); } catch (IOException e) { e.printStackTrace(); } } }
🌐
Baeldung
baeldung.com › home › java › core java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - In this article, we’ll learn how to execute a shell command from Java applications. First, we’ll use the .exec() method the Runtime class provides. Then, we’ll learn about ProcessBuilder, which is more customizable.
🌐
Mkyong
mkyong.com › home › java › java processbuilder examples
Java ProcessBuilder examples - Mkyong.com
January 19, 2019 - ProcessBuilder processBuilder = new ProcessBuilder(); // -- Linux -- // Run a shell command processBuilder.command("bash", "-c", "ls /home/mkyong/"); // Run a shell script processBuilder.command("path/to/hello.sh"); // -- Windows -- // Run a ...
🌐
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
If you have a shell script say test.sh then you can run it from a Java program using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).
🌐
Stack Overflow
stackoverflow.com › questions › 38137881 › how-to-run-sh-file-using-process-builder
java - How to run .sh file, using process builder? - Stack Overflow
April 26, 2017 - Process pb = new ProcessBuilder("/bin/bash","/my/file.sh").start(); I already looking for the answer, but I still failed to run the .sh file, even I do the same thing with people that already done it.
Top answer
1 of 1
1

In your case, you are reading something from the output stream of the process, till you consume everything. Then, you try to read error stream.

If the process writes some considerable number of characters on the error stream, the other process will block till they are consumed. To consume both error stream and output stream at the same time, you need to use threads.

You may follow the StreamGobbler technique. You may get some details from that page: https://www.javaworld.com/article/2071275/when-runtime-exec---won-t.html?page=2

This is some code influenced from the page:

public class StreamGobbler extends Thread {
    private static final String EOL = System.lineSeparator();
    private final InputStream inputStream;
    private final StringBuilder output = new StringBuilder();

    public StreamGobbler(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void run() {
        try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
             BufferedReader reader = new BufferedReader(inputStreamReader);
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line);
                output.append(EOL);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public String getOutput() {
        return output.toString();
    }
}

In your code, you use StreamGobbler like this:

    StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
    StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());

    process.waitFor();

    String commandOutput = outputGobbler.getOutput();
    String errorMessage = errorGobbler.getOutput();
    process.destroy();