greenfeet
greenfeet

Reputation: 677

Fire a cmd.exe command through ProcessBuilder with visual window

I am using this code:

ProcessBuilder builder = new ProcessBuilder("cmd.exe","java","invalidArg");
builder.redirectErrorStream(true);

try {
    Process p = builder.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()),10240);
    String line;
    if(processIsTerminated(p)){
            line = r.readLine();
    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Is there a way to have the cmd window open as well when I use the .start() function? Currently it runs hidden and if there is no response I don't know if my command was ran successfully or it didn't run at all.

Upvotes: 0

Views: 2414

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148880

Well you have only 2 ways of running a command under Windows :

  • the way you go : you have full access to the input, output and error stream of the lauched command, but it has no window and anyway it would not write anything there since your program gets all the output
  • ask cmd.exe to start the other command in its own window (and optionnaly wait for its end). But then as the command writes to its own window, you program has no access to the input, output or error streams of the command

You can obtain that 2nd execution way with the start [/w] command arguments command of cmd.exe, just type start /w cmd.exe /c "echo foo & pause" in a cmd window to see what happens (the & pause is only there to let you some time to read the output ...)

From java, it would be :

ProcessBuilder builder = new ProcessBuilder("cmd.exe","/c", "start", "/w",
    "cmd", "/c", "java invalidArg & pause");

Upvotes: 1

Related Questions