Java ProcessBuilder 从 Linux 终端命令获取输出

Java ProcessBuilder get Output from Linux Terminal Commands

我想用 java 代码与 linux 终端通信。我想存储输出并使用它。我按照给定 link 中的说明实现了下面的代码。

我希望完整的终端输出帮助。但是对于标准命令和 mosquitto 命令,我都没有从输入流中得到任何东西。错误在哪里?或者你应该完全不同吗?

Whosebug 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");
    }
}

输出:

Nothing read from input stream
Nothing read from input stream

刚刚在post之后找到解决方案:缺少“-c”部分。正确的代码片段是:

        // 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});