How to show a command executed in the console and access its output file in java

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

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

cmd /k dir - runs in the background and can read the output, but the application freezes because it requires the / k switch to switch to open the window, but I don’t see it to close it.

cmd /c start dir - opens in a new visible terminal, executes, but does not close. Closing manually does not allow me to read the output

cmd /k start dir - same result as above

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

+4
source share
2 answers
 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); } 
+4
source

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

0
source

Source: https://habr.com/ru/post/1345016/


All Articles