如何通过Java执行cmd命令 [英] How to execute cmd commands via Java

查看:44
本文介绍了如何通过Java执行cmd命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Java 执行命令行参数.例如:

I am trying to execute command line arguments via Java. For example:

// 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();

以上打开命令行但不执行cddir.有任何想法吗?我运行的是 Windows XP,JRE6.

The above opens the command line but does not execute cd or dir. Any ideas? I am running Windows XP, JRE6.

(我已将我的问题修改为更具体.以下答案很有帮助,但没有回答我的问题.)

(I have revised my question to be more specific. The following answers were helpful but do not answer my question.)

推荐答案

您发布的代码启动了三个不同的进程,每个进程都有自己的命令.要打开命令提示符然后运行命令,请尝试以下操作(我自己从未尝试过):

The code you posted starts three different processes each with it's own command. To open a command prompt and then run a command try the following (never tried it myself):

try {
    // 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();
} catch (IOException e) {
}

这篇关于如何通过Java执行cmd命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆