Java 向进程发送输入

Java 向进程发送输入,java,process,runtime.exec,Java,Process,Runtime.exec,我有这个代码,它工作得很好。如何将输入发送到Java Process Builder 代码如下: PrintStream out = System.out; Runtime rt = Runtime.getRuntime(); try { out.println("Executing a command in a separate process..."); Scanner input = new Scanner(System.in); String str =

我有这个代码,它工作得很好。如何将输入发送到Java Process Builder

代码如下:

PrintStream out = System.out;
Runtime rt = Runtime.getRuntime(); 
try {
     out.println("Executing a command in a separate process...");
     Scanner input = new Scanner(System.in);
     String str = input.nextLine();
     Process proc = rt.exec(str);

     /*OutputStream procIn = proc.getOutputStream();
     procIn.write("My Code".getBytes());
     procIn.close();*/

     InputStream procOut = proc.getInputStream();
     byte[] msgOut = new byte[64];
     int len = procOut.read(msgOut);
     procOut.close();
     out.println("Output from the command: "
        +new String(msgOut,0,len));

     out.println("Waiting for the process to finish...");
     int rc = proc.waitFor();
     out.println("Status code returned by the process "+rc);
  } catch (Exception e) {
     e.printStackTrace();
  }
我需要知道如何使用此部分:

/*OutputStream procIn = proc.getOutputStream();
     procIn.write("My Code".getBytes());
     procIn.close();*/

提前感谢您的帮助。

您需要一个单独的线程,该线程可以写入进程的
OutputStream
,直到
waitFor
退出……您可以发送一个关于它的工作代码吗……试试,别忘了汇款;)阅读(并实施)的所有建议。这可能会解决问题。如果没有,它应该提供更多关于失败原因的信息。然后忽略它引用的
exec
,并使用
ProcessBuilder
构建
流程。还可以将
字符串arg
分解为
字符串[]args
,以说明本身包含空格的参数。