java Runtime.exec 到 运行 交互式 shell 挂起

java Runtime.exec to run interactive shell hangs

我尝试在 java 中执行 windows 命令 cmd,向其提供命令并在控制台上打印输出或错误。但是,我的尝试在打印横幅消息后挂起。这是代码。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class Application {

    public static void main(String[] args) throws IOException, InterruptedException {

        Process exec = Runtime.getRuntime().exec("cmd");

        InputStream procOut = exec.getInputStream();
        InputStream procErrOut = exec.getErrorStream();
        OutputStream procIn = exec.getOutputStream();

        new StreamConsumer(procOut).run();
        new StreamConsumer(procErrOut).run();

        ByteArrayOutputStream byos = new ByteArrayOutputStream();
        byos.write("ping 1.1.1.1".getBytes());
        byos.writeTo(procIn);
        byos.flush();
        procIn.flush();

        int ret = exec.waitFor();
        System.out.printf("Process exited with value %d", ret);
    }

    public static class StreamConsumer implements Runnable {

        private InputStream input;

        public StreamConsumer(InputStream input) {
            this.input = input;
        }

        @Override
        public void run() {
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }
}

这是输出

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
** program hangs **

为什么程序挂起并且没有执行(或打印)ping?我知道必须消耗流以避免挂起(我在单独的线程中这样做),但它仍然挂起。我是不是误解了输出流是如何通过管道传输到交互式 shell 或者是什么问题?

您必须启动线程才能使用输出:

        new Thread(new StreamConsumer(procOut)).start();
        new Thread(new StreamConsumer(procErrOut)).start();