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,
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);
The output looks like this:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:(Current Directory)>
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…