2013-06-19 67 views
0

我試圖寫一個程序,有toexecute在Linux終端相同的代碼:Java和調用Runtime.getRuntime()EXEC(字符串CMD)

openssl req -passout pass:abc -subj /C=US/ST=IL/L=Chicago/O=IBM   Corporation/OU=IBM Software Group/CN=John Smith/[email protected] -new > johnsmith.cert.csr 

在正常工作的終端,但在Java中它沒有。 我嘗試這樣的事情,但沒有結果。

String[] cmd = { "openssl", "req -passout pass:abc -subj", "/C=US/ST=IL/L=Chicago/O=IBM   Corporation/OU=IBM Software Group/CN=John Smith/[email protected]", "-new > johnsmith.cert.csr" }; 
Runtime.getRuntime().exec(cmd); 

你能解釋我嗎,我想念什麼。提前感謝。 祝福安德烈

+2

您是否嘗試過:'Runtime.getRuntime()。exec(「openssl req -passout pass:abc -subj/C = US/ST = IL/L = Chicago/O = IBM Corporation/OU = IBM Software Group/CN = John Smith/[email protected] -new> johnsmith.cert.csr「);'? – assylias

+2

您是否看到任何錯誤?如果是,那麼錯誤信息是什麼? – helios

+0

閱讀(並實現)*所有* [Runtime.exec()不會](http://www.javaworld.com/jw-12-2000/jw-1229-traps.html)的建議。這可能會解決問題。如果不是,它應該提供更多關於失敗原因的信息。然後忽略它引用'exec'並使用'ProcessBuilder'構建'Process'。還要將'String arg'分解爲'String [] args'來解釋其本身包含空格的參數。 –

回答

1

您錯過了流重定向>是這裏不存在的shell的功能的事實。

您可以在前面加上你的命令/bin/sh -c或使用Java重定向輸出:

Process proc = Runtime.getRuntime().exec(cmd); 
InputStream in = proc.setOutputStream(); 
OutputStream out = new FileOutputStream("johnsmith.cert.csr"); 
int b; 
while((b = in.read()) != -1) { 
    out.write(b); 
} 
out.flush(); 
out.close(); 

現在,您可以從您的命令行刪除"> johnsmith.cert.csr"。我個人更喜歡這個解決方案。

+0

謝謝。我發現我的命令中有syntacsys錯誤,但是您對該文件是正確的。謝謝 – user2501809

相關問題