想在java虛擬機調用外部程序 第一個想到的應是java.lang.runtime 然后利用runtime.exec方法得到PRocess進程 但是這個方法有很多坑,例如不及時讀取緩沖中的數據時,就會掛死
后來發現了apache.commons.executor這個類 他在內部已經做好了足夠的準備 至少不會發生掛死的情況
import org.apache.commons.exec.CommandLine;import org.apache.commons.exec.DefaultExecutor;import org.apache.commons.exec.PumpStreamHandler;//CommandLine command = CommandLine.parse("echo 123456789"); 和下面的是一樣的CommandLine command = new CommandLine("echo");command.addArgument("1234");DefaultExecutor executor = new DefaultExecutor();// 如果需要讀取輸出,則需要設置下列步驟ByteArrayOutputStream outputStream = new ByteArrayOutputStream();PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); // 如果需要在其他目錄下工作,需要設置以下兩步File workingDirectory = new File("/home/user/")executor.setWorkingDirectory(workingDirectory);try { executor.execute(commandLine);} catch (final IOException e) { e.printStackTrace();}System.out.println(outputStream.toString());// 讀取輸出上述程序將會輸出1234
,值得注意的是,如果不設置streamHandler,程序會自動輸出到console
新聞熱點
疑難解答