如何通过Java执行命令行参数
问题:
如何执行通过 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中文网其他相关文章!