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

时间:2018-07-30 11:28:06

标签: java linux processbuilder

我想用Java代码与linux终端通信。我想存储输出并使用它。我按照给定链接中的说明实施了以下代码。

我希望获得完整的帮助终端输出。但是无论对于标准命令还是mo​​squitto命令,我都无法从输入流中得到任何东西。错误在哪里?还是应该完全不同?

Stackoverflow链接: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");
    }
}

输出:

  

什么也没从输入流中读取
什么也没从输入流中读取

1 个答案:

答案 0 :(得分:0)

在帖子发布后立即找到了解决方案:“-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});