0

I want to run some commands from Java, but the following program does not print out the expected result. Any ideas?

import java.io.IOException;

public class MyClass {
    public static void main(String args[]) throws IOException {


          Process p = new ProcessBuilder("gcc", "--version").start();

    }
}
zell
  • 9,830
  • 10
  • 62
  • 115
  • 2
    Your code does not try to print anything, so an empty output is to be expected. Look at the `Process` class' javadoc and look for how to handle the process' output stream – Aaron Apr 25 '22 at 10:59

1 Answers1

3

You need to set the source and destination for subprocess standard I/O to be the same as those of the current Java process. You can to this by calling:

ProcessBuilder.inheritIO();

So your example should look something like:

import java.io.IOException;

public class MyClass {

    public static void main(String args[]) throws IOException {
          ProcessBuilder processBuilder = new ProcessBuilder("gcc", "--version");
          processBuilder.inheritIO();
          processBuilder.start()
    }

}

For advanced process I/O usage you should take a look at ProcessBuilder and Process JavaDocs.

PrimosK
  • 13,848
  • 10
  • 60
  • 78