调用Runtime.exec时如何捕获标准输出

58

当客户端机器遇到网络问题时,我希望能运行一些命令并将它们的结果发送到我的电子邮件中。

我发现 Runtime.exec 可以让我执行任意命令,但是将结果收集到字符串中更加有趣。

我知道可以将输出重定向到文件,然后从文件中读取,但是我的直觉告诉我有一种更加优雅的方法。

您有什么建议吗?


请查看此文章 - kgiannakakis
8个回答

48
你需要同时捕获进程的标准输出和标准错误信息。然后,你可以将标准输出写入文件/邮件或类似的位置。参见本文获取更多信息,特别注意StreamGobbler机制,它可以在单独的线程中捕获stdout/err。这对于防止阻塞非常重要,如果不正确处理该机制,则会导致许多错误!

1
我注意到,如果命令产生了大量输出,代码流程将在 Gobblers 完成输出之前继续。需要在返回之前调用 .join()。 - Zitrax
@Odelya - 我不相信这是特定于操作系统的。 - Brian Agnew
这不是特定于平台的。 - Brian Agnew
文章的链接已经失效。 - Paul Wintz
已更新为新链接。 - Brian Agnew
显示剩余3条评论

16

使用ProcessBuilder。调用start()方法后,您将获得一个Process对象,从中可以获取stderr和stdout流。

更新:ProcessBuilder提供更多控制;您不必使用它,但我发现长期来看更容易。特别是能够将stderr重定向到stdout,这意味着您只需要下载一个流。


4
我该如何从“OutputStream”中获取输出? - pihentagy

7
使用Plexus工具,它被Maven用于执行所有外部进程。
Commandline commandLine = new Commandline();
commandLine.setExecutable(executable.getAbsolutePath());

Collection<String> args = getArguments();

for (String arg : args) {
    Arg _arg = commandLine.createArg();
    _arg.setValue(arg);
}

WriterStreamConsumer systemOut = new WriterStreamConsumer(console);
WriterStreamConsumer systemErr = new WriterStreamConsumer(console);

returnCode = CommandLineUtils.executeCommandLine(commandLine, systemOut, systemErr, 10);
if (returnCode != 0) {
    // bad
} else {
    // good
}

2
为什么在核心语言已经有完全合适的替代方案时还要使用外部库呢? - PaulJWilliams
2
有些差异可能一开始看不出来。
  1. 如果您调用Process.waitFor(),它将会阻塞,这意味着您必须读取进程输出,否则进程将等待输出缓冲区(控制台输出)可用。如果您选择此路径(自行获取输出),则不得使用waitFor()。
  2. 如果您轮询,则必须添加代码来处理在等待读取输出时发生的情况。
Plexus Utils-246k等库的目的是帮助您避免重复造轮子 :)
- adrian.tarau
Ant会做同样的事情,如果你想要可以使用它,有一个核心任务可以被调用(在适当初始化Ant上下文的情况下)来执行此任务,但我更喜欢Plexus Utils,因为它更小(你甚至可以剥离除了cli包之外的一切,这意味着你只有不到50k),专注且被证明是稳定的(因为它包含在Maven 2中)。 - adrian.tarau

7

对于不会生成大量输出的进程,我认为这个简单的解决方案可以使用Apache IOUtils

Process p = Runtime.getRuntime().exec("script");
p.waitFor();
String output = IOUtils.toString(p.getInputStream());
String errorOutput = IOUtils.toString(p.getErrorStream());

注意:然而,如果您的进程生成大量输出,则此方法可能会导致问题,如Process类JavaDoc中所述:
创建的子进程没有自己的终端或控制台。它所有的标准IO操作(即stdin、stdout和stderr)都将通过三个流(getOutputStream()、getInputStream()和getErrorStream())重定向到父进程。父进程使用这些流来为子进程提供输入并获取输出。由于一些本地平台仅为标准输入和输出流提供有限的缓冲区大小,因此未能及时写入子进程的输入流或读取子进程的输出流可能会导致子进程阻塞,甚至死锁。

5

这是我多年来一直在使用的帮助类。它只有一个小类,其中包含JavaWorld streamgobbler类以修复JVM资源泄漏问题。虽然不确定是否适用于JVM6和JVM7,但不会造成任何伤害。此帮助程序可以读取输出缓冲区以供稍后使用。

import java.io.*;

/**
 * Execute external process and optionally read output buffer.
 */
public class ShellExec {
    private int exitCode;
    private boolean readOutput, readError;
    private StreamGobbler errorGobbler, outputGobbler;

    public ShellExec() { 
        this(false, false);
    }

    public ShellExec(boolean readOutput, boolean readError) {
        this.readOutput = readOutput;
        this.readError = readError;
    }

    /**
     * Execute a command.
     * @param command   command ("c:/some/folder/script.bat" or "some/folder/script.sh")
     * @param workdir   working directory or NULL to use command folder
     * @param wait  wait for process to end
     * @param args  0..n command line arguments
     * @return  process exit code
     */
    public int execute(String command, String workdir, boolean wait, String...args) throws IOException {
        String[] cmdArr;
        if (args != null && args.length > 0) {
            cmdArr = new String[1+args.length];
            cmdArr[0] = command;
            System.arraycopy(args, 0, cmdArr, 1, args.length);
        } else {
            cmdArr = new String[] { command };
        }

        ProcessBuilder pb =  new ProcessBuilder(cmdArr);
        File workingDir = (workdir==null ? new File(command).getParentFile() : new File(workdir) );
        pb.directory(workingDir);

        Process process = pb.start();

        // Consume streams, older jvm's had a memory leak if streams were not read,
        // some other jvm+OS combinations may block unless streams are consumed.
        errorGobbler  = new StreamGobbler(process.getErrorStream(), readError);
        outputGobbler = new StreamGobbler(process.getInputStream(), readOutput);
        errorGobbler.start();
        outputGobbler.start();

        exitCode = 0;
        if (wait) {
            try { 
                process.waitFor();
                exitCode = process.exitValue();                 
            } catch (InterruptedException ex) { }
        }
        return exitCode;
    }   

    public int getExitCode() {
        return exitCode;
    }

    public boolean isOutputCompleted() {
        return (outputGobbler != null ? outputGobbler.isCompleted() : false);
    }

    public boolean isErrorCompleted() {
        return (errorGobbler != null ? errorGobbler.isCompleted() : false);
    }

    public String getOutput() {
        return (outputGobbler != null ? outputGobbler.getOutput() : null);        
    }

    public String getError() {
        return (errorGobbler != null ? errorGobbler.getOutput() : null);        
    }

//********************************************
//********************************************    

    /**
     * StreamGobbler reads inputstream to "gobble" it.
     * This is used by Executor class when running 
     * a commandline applications. Gobblers must read/purge
     * INSTR and ERRSTR process streams.
     * http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
     */
    private class StreamGobbler extends Thread {
        private InputStream is;
        private StringBuilder output;
        private volatile boolean completed; // mark volatile to guarantee a thread safety

        public StreamGobbler(InputStream is, boolean readStream) {
            this.is = is;
            this.output = (readStream ? new StringBuilder(256) : null);
        }

        public void run() {
            completed = false;
            try {
                String NL = System.getProperty("line.separator", "\r\n");

                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ( (line = br.readLine()) != null) {
                    if (output != null)
                        output.append(line + NL); 
                }
            } catch (IOException ex) {
                // ex.printStackTrace();
            }
            completed = true;
        }

        /**
         * Get inputstream buffer or null if stream
         * was not consumed.
         * @return
         */
        public String getOutput() {
            return (output != null ? output.toString() : null);
        }

        /**
         * Is input stream completed.
         * @return
         */
        public boolean isCompleted() {
            return completed;
        }

    }

}

以下是一个来自.vbs脚本的例子输出,但类似的适用于Linux sh脚本。
   ShellExec exec = new ShellExec(true, false);
   exec.execute("cscript.exe", null, true,
      "//Nologo",
      "//B",            // batch mode, no prompts
      "//T:320",        // timeout seconds
      "c:/my/script/test1.vbs",  // unix path delim works for script.exe
      "script arg 1",
      "script arg 2",
   );
   System.out.println(exec.getOutput());

2

VerboseProcess是来自jcabi-log的实用工具类,可以帮助您:

String output = new VerboseProcess(
  new ProcessBuilder("executable with output")
).stdout();

你只需要一个依赖:

只需要这个依赖:

<dependency>
  <groupId>com.jcabi</groupId>
  <artifactId>jcabi-log</artifactId>
  <version>0.7.5</version>
</dependency>

1

Runtime.exec() 返回一个 Process 对象,你可以从中提取你运行的任何命令的输出。


1
使用Runtime.exec可以得到一个进程。您可以使用getInputStream来获取此进程的标准输出,并将此输入流放入一个字符串中,例如通过StringBuffer。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接