The Burger
The Burger

Reputation: 43

How to show command executing in the console and access its output in java

I have a command line tool that queries a server and prints the status of pending jobs to run. This can take up to 30 seconds. I need to call this tool from java and I want to show its output in a text area on my GUI. For the purposes of example, lets say the command is "dir" in windows.

Process.getRuntime().exec("cmd /c dir"); blocks until the command finishes executing, so I thought it would be best to show the command executing in the terminal, then read the output and show it in my text area for future reference. However, the console is hidden giving the user the impression that the application has stopped working. After much research, I have tried:

cmd /k dir - runs in the background and can read output, but application hangs as it requires the /k switch means to keep the window open, but I can't see it to close it.

cmd /c start dir - opens in a new visible terminal, runs but doesn't close. Closing manually doesn't allow me to read the output

cmd /k start dir - same result as above

My question is, how can I spawn a command to run, see it running, and access its output?

Upvotes: 4

Views: 8837

Answers (2)

Brian Roach
Brian Roach

Reputation: 76918

Process proc = null;
String[] cmd = { "cmd", "/c", "dir" };
proc = Runtime.getRuntime().exec(cmd);

InputStream inputStream = proc.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String line;
while ((line = bufferedReader.readLine()) != null)
{
    System.out.println(line);
}

Upvotes: 4

MByD
MByD

Reputation: 137432

You can grab its input / output / error stream using the process methods. but you need to get the process object - Process p = Process.getRuntime().exec("cmd /c dir"); see this answer also.

Upvotes: 0

Related Questions