Affi
Affi

Reputation: 152

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();
        }
    }

Upvotes: 2

Views: 1635

Answers (2)

Sergio
Sergio

Reputation: 1

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

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

    public String getOutput() {
        return output.toString();
    }
}

Upvotes: -1

wero
wero

Reputation: 33010

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);
 ...

Upvotes: 4

Related Questions