在Java中重定向stdin和stdout

Jos*_*osh 4 java stdin stdout process

我正在尝试重定向java中的子进程的stdin和stdout,最终我将输出转到JTextArea或其他东西.

这是我目前的代码,

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

cmd.getOutputStream().write("echo Hello World".getBytes());
cmd.getOutputStream().flush();

byte[] buffer = new byte[1024];
cmd.getInputStream().read(buffer);
String s = new String(buffer);

System.out.println(s);
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

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

C:\(Current Directory)>
Run Code Online (Sandbox Code Playgroud)

我期待看到输出的"Hello World"字符串.也许是因为父进程没有足够长久存活?

我也希望能够发送和接收多个命令.

Hov*_*els 9

在尝试侦听输入流之前,您已尝试写入输出流,因此您没有看到任何内容.为了成功,您需要为两个流使用单独的线程.

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class Foo {
   public static void main(String[] args) throws IOException {
      Process cmd = Runtime.getRuntime().exec("cmd.exe");

      final InputStream inStream = cmd.getInputStream();
      new Thread(new Runnable() {
         public void run() {
            InputStreamReader reader = new InputStreamReader(inStream);
            Scanner scan = new Scanner(reader);
            while (scan.hasNextLine()) {
               System.out.println(scan.nextLine());
            }
         }
      }).start();

      OutputStream outStream = cmd.getOutputStream();
      PrintWriter pWriter = new PrintWriter(outStream);
      pWriter.println("echo Hello World");
      pWriter.flush();
      pWriter.close();
   }
}
Run Code Online (Sandbox Code Playgroud)

你真的不应该忽略错误流,而是应该吞噬它,因为忽略它有时会炸掉你的进程,因为它可能会耗尽缓冲区空间.


Ósc*_*pez 6

现在Runtime.getRuntime().exec()已被弃用(出于所有实际目的).更好地使用ProcessBuilder类; 特别是,它的start()方法将返回一个Process对象,其中包含访问stdin和stdout流的方法,可以将它们重定向到您需要的地方.请查看此帖子了解更多详情.