简体   繁体   English

Linux中未捕获linux命令的输出

[英]The output of linux command is not captured in java

I am trying to run the below command from java and want to capture the output. 我正在尝试从Java运行以下命令,并希望捕获输出。 The method is getting completed immediately without writing anything to the console. 该方法将立即完成,而无需向控制台写入任何内容。

Linux Command is repo forall -c 'echo pwd is;pwd;git status' and the method is Linux命令是repo forall -c 'echo pwd is;pwd;git status'并且方法是

public static String executeCommandWithOutput(String command) {
    System.out.println("Running the command "+command);
    StringBuffer output = new StringBuffer();
    String line = "";
    try {
        Process process =Runtime.getRuntime().exec(command);
        process.waitFor();

        BufferedReader reader = 
            new BufferedReader(new InputStreamReader(process.getInputStream()));
        while ((line = reader.readLine())!= null) {
            output.append(line);
        }
        System.out.println("Content is "+output.toString());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return output.toString();
}

I tried redirecting the output to a file as well. 我也尝试将输出重定向到文件。 Neither worked. 两者都不起作用。 Any thoughts?? 有什么想法吗??

Check if the command your are trying to execute has a standard output. 检查您尝试执行的命令是否具有标准输出。

Probably its failing and you are getting error output. 可能是它失败了,您正在得到错误输出。

You can check the error output with getErrorStream , documentation is here . 您可以使用getErrorStream检查错误输出,文档在这里

Eg like this 例如这样

StringBuffer error = new StringBuffer();

BufferedReader reader = 
    new BufferedReader(new InputStreamReader(process.getErrorStream()));

while ((line = reader.readLine())!= null) {
        error.append(line);
}

System.out.println("Error is " + error.toString());

Also check the exitValue of your forked command, doc is here 还要检查您的分叉命令的exitValue ,doc在这里

int exitStatus = process.exitValue();

System.out.println("Exit status is " + exitStatus );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM