Search code examples
javaprocessbuilder

ProcessBuilder not displaying output stream if it is java


I got a code which is running and displaying output successfully if I am executing something like "dir" but not displaying the output if I am running "java -version" or other command from java. Please help:

public static void execJob(){

    try{        

    ProcessBuilder pb = new ProcessBuilder("C:\\myPrograms\\jdk1.7.0_79\\bin\\java.exe", "-version");
    pb.directory(new File("src"));
    Process process = pb.start();
    IOThreadHandler outputHandler = new IOThreadHandler(process.getInputStream());
    outputHandler.start();
    process.waitFor();

    System.out.println(outputHandler.getOutput());
    }catch(Exception e) {
        System.out.println(e.toString());
    }

}

private static class IOThreadHandler extends Thread {
    private InputStream inputStream;
    private StringBuilder output = new StringBuilder();

    IOThreadHandler(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void run() {
        Scanner br = null;
        try {
            br = new Scanner(new InputStreamReader(inputStream));
            String line = null;
            while (br.hasNextLine()) {
                line = br.nextLine();
                output.append(line + System.getProperty("line.separator"));
            }
        } finally {
            br.close();
        }
    }

Solution

  • java -version writes to stderr, so you need pb.redirectErrorStream(true); to capture the output.

     ProcessBuilder pb = new ProcessBuilder("C:\\myPrograms\\jdk1.7.0_79\\bin\\java.exe", "-version");
     pb.redirectErrorStream(true);
     ...