Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get command prompt output in java?

How to get the output of the command prompt which means i have opend a command prompt like this.

Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"C:\\Editor\\editorTemp.exe\"");

i can not get the cmd output like this

BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

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

So how can i get the command prompt output ?

like image 876
Harshana Samaranayake Avatar asked Dec 05 '25 07:12

Harshana Samaranayake


1 Answers

This is not Java question. Basically what you doing is running Java (Java Main Process A) and from it starting another process (Windows CMD B). This is fine and you can get input/output streams of this process (B) in Java(A). However this process (B) starts another process (again Windows CMD C) with its own standard input/output. This process has nothing common with processes A&B and uses Windows' standard Input/Output streams. So, there are no connections between A and C. I'm not sure but I think there are some ways to run Windows CMD with different or not standard IO. Maybe something like this will work:

cmd <tty >tty

but there is no tty in Windows. Pragmatically you can do this as described here - Creating a Child Process with Redirected Input and Output but that would not work for regular CMD.

Nevertheless it became even more problematic when you start your own process from the editorTemp.exe (process D). D has even more disconnection with process A. And all for what? What don't you simply start process D directly from A and have full control on the IO streams and process itself? Here is good example how to do so.

like image 121
Alex Avatar answered Dec 07 '25 20:12

Alex