How to execute cmd commands via Java

2018-12-31 18:24发布

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

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.)

标签: java exec
9条回答
何处买醉
2楼-- · 2018-12-31 18:40

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) {
}
查看更多
君临天下
3楼-- · 2018-12-31 18:47

As i also faced the same problem and because some people here commented that the solution wasn't working for them, here's the link to the post where a working solution has been found.

https://stackoverflow.com/a/24406721/3751590

Also see the "Update" in the best answer for using Cygwin terminal

查看更多
ら面具成の殇う
4楼-- · 2018-12-31 18:48

Try this link

You do not use "cd" to change the directory from which to run your commands. You need the full path of the executable you want to run.

Also, listing the contents of a directory is easier to do with the File/Directory classes

查看更多
登录 后发表回答