【问题标题】:Java ProcessBuilder get Output from Linux Terminal CommandsJava ProcessBuilder 从 Linux 终端命令获取输出
【发布时间】:2019-01-06 15:30:11
【问题描述】:

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

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

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

输出:

没有从输入流中读取
没有从输入流中读取

【问题讨论】:

    标签: java linux processbuilder


    【解决方案1】:

    在帖子发布后立即找到了解决方案:缺少“-c”部分。正确的代码 sn -p 是:

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

    【讨论】:

    • 在测试期间至少使用ProcessBuilder#redirectErrorStream(true) 会合并标准输出和标准错误,并有助于更快地发现这类错误。
    猜你喜欢
    • 1970-01-01
    • 2013-02-01
    • 2013-09-06
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    相关资源
    最近更新 更多