如何透過Java執行指令列參數
問題:
如何執行通過透過透過透過來執行透過完成透過完成器的命令列參數?例如,考慮以下程式碼:
// Execute command String command = "cmd /c start cmd.exe"; Process child = Runtime.getRuntime().exec(command); // Get output stream to write from it OutputStream out = child.getOutputStream(); out.write("cd C:/ /r/n".getBytes()); out.flush(); out.write("dir /r/n".getBytes()); out.close();
此程式碼開啟命令列,但不執行「cd」或「dir」命令。
答案:
要在Windows 中為多個指令重複使用單一行程,請遵循下列步驟步驟:
這是一個例如:
String[] command = {"cmd"}; Process p = Runtime.getRuntime().exec(command); new Thread(new SyncPipe(p.getErrorStream(), System.err)).start(); new Thread(new SyncPipe(p.getInputStream(), System.out)).start(); PrintWriter stdin = new PrintWriter(p.getOutputStream()); stdin.println("dir c:\ /A /Q"); stdin.close(); int returnCode = p.waitFor(); System.out.println("Return code = " + returnCode);
SyncPipe 類別:
class SyncPipe implements Runnable { public SyncPipe(InputStream istrm, OutputStream ostrm) { istrm_ = istrm; ostrm_ = ostrm; } public void run() { try { final byte[] buffer = new byte[1024]; for (int length = 0; (length = istrm_.read(buffer)) != -1; ) { ostrm_.write(buffer, 0, length); } } catch (Exception e) { e.printStackTrace(); } } private final OutputStream ostrm_; private final InputStream istrm_; }
以上是如何在Java中正確執行多個命令列命令?的詳細內容。更多資訊請關注PHP中文網其他相關文章!