Redirect stdin and stdout in Java

后端 未结 2 714
小鲜肉
小鲜肉 2020-12-03 09:05

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.

Here is my current code,

相关标签:
2条回答
  • 2020-12-03 09:39

    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.

    i.e.,

    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.

    0 讨论(0)
  • 2020-12-03 09:40

    Nowadays Runtime.getRuntime().exec() is deprecated (for all practical purposes). Better use the ProcessBuilder class; in particular, its start() method will return a Process object with methods for accessing the stdin and stdout streams, which can be redirected wherever you need them. Take a look at this post for further details.

    0 讨论(0)
提交回复
热议问题