Search code examples
javalinuxprocessbuilder

Java ProcessBuilder get Output from Linux Terminal Commands


I want to communicate with the linux terminal with java code. I want to store the output and work with it. I implemented the code below following the instructions in given link.

I would expect the complete terminal output of help. But neither for the standard commands, nor for the mosquitto commands I get anything from the input stream. Where is the mistake? Or are you supposed to do it completely differnt?

Stackoverflow link: how to run a command at terminal from java program?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class LinuxInputStream
{
    public static void main(String[] args)
    {
        // Linux Terminal
        String prefix = "/bin/bash";
        String terminalCommand = "help";
        String mosquittoCommand = "mosquitto --help";

        ProcessBuilder pb1 = new ProcessBuilder(
                new String[] {prefix, terminalCommand});
        ProcessBuilder pb2 = new ProcessBuilder(
                new String[] {prefix, mosquittoCommand});

        try
        {
            executeCommand(pb1);
        }
        catch (IOException e)
        {
            System.out.println("IO Error in Terminal Command execution!");
            e.printStackTrace();
        }
        try
        {
            executeCommand(pb2);
        }
        catch (IOException e)
        {
            System.out.println("IO Error in Mosquitto Command execution!");
            e.printStackTrace();
        }

    }

    private static void executeCommand(ProcessBuilder pb) throws IOException
    {
        Process terminalCommandProcess = pb.start();
        InputStream inputStream = terminalCommandProcess.getInputStream();
        BufferedReader br = new BufferedReader(
                new InputStreamReader(inputStream));
        String line;
        int i = 0;
        while ((line = br.readLine()) != null)
        {
            System.out.println("Line: " + line);
            i++;
        }
        if (i == 0) System.out.println("Nothing read from input stream");
    }
}

Output:

Nothing read from input stream
Nothing read from input stream


Solution

  • Just found the solution immidiatly after the post: The "-c" part is missing. Correct code snippet is:

            // Linux Terminal
            String prefix = "/bin/bash";
            String c = "-c";
            String terminalCommand = "help";
            String mosquittoCommand = "mosquitto --help";
    
            ProcessBuilder pb1 = new ProcessBuilder(
                    new String[] {prefix, c, terminalCommand});
            ProcessBuilder pb2 = new ProcessBuilder(
                    new String[] {prefix, c, mosquittoCommand});