如何使用java中的流将命令发送到命令提示符

时间:2017-02-03 22:08:10

标签: java process stream

我试图使用流将命令传递给commandLine。我使用ProcessBuilder来启动这个过程。 运行代码后,会弹出commandLine但字符串不会传递给commandLine。 我为输入和输出流创建了单独的线程,进程永远不会被终止。

        public static void main(String[] args) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder("cmd.exe","/c","start");
    pb.redirectOutput(Redirect.INHERIT);
    pb.redirectError(Redirect.INHERIT);
    Process p = pb.start();
    final InputStream is = p.getInputStream();
    OutputStream os = p.getOutputStream();


    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            try
            {

                PrintWriter s = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os)));
                s.write("1");
                s.write("\n");
                s.flush();
                System.out.println("Pass written");
            }
            catch(Exception e)
            {
                System.out.println("Exception raised in writer thread"+ e);
            }
        }
    }).start();

    new Thread(new Runnable()
    {

        @Override
        public void run()
        {
            try
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String s;
                while (( s=reader.readLine()) != null) {
                    System.out.println(s);
                }
            }
            catch(Exception e)
            {
                System.out.println("Exception raised in reader thread"+ e);
            }
        }
    }).start();

    int returnVal = p.waitFor();
    System.out.println("Process ended with return val "+ returnVal);

}

0 个答案:

没有答案