I'm not getting any output and probably the machine hangs with the code [duplicate]

pro.waitFor(); is a blocking method. It will wait until the process has exited before returning. The problem with this is many programs will not exit until there standard out buffers have been read/cleared, meaning, in your case, it probably will never exit.

Try something like this instead…

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class PBDemo {

    public static void main(String[] args) throws Exception {
        String s;
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "dir");
        pb.directory(new File("C:\\ljava"));
        try {
            Process pro = pb.start();
            InputConsumer ic = new InputConsumer(pro.getInputStream());
            int exitCode = pro.waitFor();


            System.out.println("Process exited with " + exitCode);

        } catch (Exception e) {
            System.out.println("sorry" + e);

    public static class InputConsumer extends Thread {

        private InputStream is;

        public InputConsumer(InputStream is) {
            this.is = is;

        public void run() {
//            This is acutally a bad idea, not all process will write a new line ;)
//            BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));

            try {
                int in = -1;
                while ((in = is.read()) != -1) {
                    System.out.print((char) in);
            } catch (IOException exp) {



Browse More Popular Posts

Leave a Comment