user234194
user234194

Reputation: 1723

opening cmd prompt and execute command java

I was able to open a command prompt from my Java program with the following code:

String cmd = "C:\\WINNT\\system32\\cmd.exe /c start";


    try {
        @SuppressWarnings("unused")
        Process ps = Runtime.getRuntime().exec(cmd);
    } catch (IOException e) {
        e.printStackTrace();
    }

The above code opens the command prompt.

If I want to execute some command in this opened command prompt , what I have to do?

ANy help is appreciated.

Upvotes: 0

Views: 3820

Answers (2)

limc
limc

Reputation: 40160

I think you are at the right direction. To execute some commands or more than one command, repeat the cmd /k [command], like this:-

// write dir output to file
Runtime.getRuntime().exec(new String[] {
        "cmd",
        "/k",
        "dir",
        ">",
        "c:\\output.txt"
});

// create test-dir folder in c:\
Runtime.getRuntime().exec(new String[] {
        "cmd",
        "/k",
        "mkdir",
        "c:\\test-dir"
});

Upvotes: 1

murgatroid99
murgatroid99

Reputation: 20232

I know that cmd /k [some other command] will run that command in the command prompt, but it only runs one, so it is a limited solution

Upvotes: 0

Related Questions