【问题标题】:How to execute an external command and capture the output? [closed]如何执行外部命令并捕获输出? [关闭]
【发布时间】:2016-05-16 09:22:55
【问题描述】:

在 java 中,如何执行外部命令(如 windows 中的 cmd 或 Linux 中的 terminal),并在命令执行后捕获结果?

【问题讨论】:

  • 不清楚你有什么问题。看看Minimal, Complete, and Verifiable example,向我们展示您迄今为止所做的事情以及您的期望。
  • @gfelisberto 我已将他的问题编辑得更清楚。
  • 网络上有数百个示例,这里有关于如何执行此操作的示例。目前尚不清楚 OP 对“经典”解决方案有什么问题。

标签: java windows file cmd processbuilder


【解决方案1】:

为此考虑Apache Commons Exec

It is a simple,但实现多平台命令行调用的可靠框架。

这是执行命令并将结果输出为String 实例的示例方法。

import java.io.ByteArrayOutputStream;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;

public String execToString(String command) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine commandline = CommandLine.parse(command);
    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    exec.execute(commandline);
    return(outputStream.toString());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2014-07-31
    • 2017-08-15
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多