2016-05-16 121 views
-1

在java中,如何執行外部命令(例如,在windows中的cmd或Linux中的terminal),並在命令執行後捕獲結果?如何執行外部命令並捕獲輸出?

+0

目前還不清楚你有什麼問題。查看[最小化,完整和可驗證的示例](http://stackoverflow.com/help/mcve),並向我們展示您迄今爲止所做的以及您的期望。 – gfelisberto

+0

@gfelisberto我已經編輯了他的問題,以便更清楚。 – 2016-05-16 09:30:40

+0

網絡中有數百個示例,以及關於如何執行此操作的SO。目前還不清楚OP與「經典」解決方案存在哪些問題。 – gfelisberto

回答

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()); 
} 
相關問題