在 Java 中重定向标准输入和标准输出 [英] Redirect stdin and stdout in Java

查看:23
本文介绍了在 Java 中重定向标准输入和标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to redirect stdin and stdout of a subprocess in java, eventually i'm going to have the output go to a JTextArea or something.

这是我当前的代码,

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);

输出如下:

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

C:(Current Directory)>

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

I'm expecting to see the "Hello World" string outputted. Maybe because the parent process isn't staying alive long enough?

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

I'd also like to be able to send and receive multiple commands.

推荐答案

您在尝试侦听输入流之前已尝试写入输出流,因此您什么也没看到是有道理的.为此,您需要为两个流使用单独的线程.

You've attempted to write to the output stream before you attempt to listen on the input stream, so it makes sense that you're seeing nothing. For this to succeed, you will need to use separate threads for your two streams.

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();
   }
}

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

And you really shouldn't ignore the error stream either but instead should gobble it, since ignoring it will sometimes fry your process as it may run out of buffer space.

这篇关于在 Java 中重定向标准输入和标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆