Created
March 31, 2012 14:26
-
-
Save pditommaso/2265496 to your computer and use it in GitHub Desktop.
Read/write input/output stream of interactive process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
public class TestProcessIO { | |
public static boolean isAlive(Process p) { | |
try { | |
p.exitValue(); | |
return false; | |
} | |
catch (IllegalThreadStateException e) { | |
return true; | |
} | |
} | |
public static void main(String[] args) throws IOException { | |
ProcessBuilder builder = new ProcessBuilder("bash", "-i"); | |
builder.redirectErrorStream(true); // so we can ignore the error stream | |
Process process = builder.start(); | |
InputStream out = process.getInputStream(); | |
OutputStream in = process.getOutputStream(); | |
byte[] buffer = new byte[4000]; | |
while (isAlive(process)) { | |
int no = out.available(); | |
if (no > 0) { | |
int n = out.read(buffer, 0, Math.min(no, buffer.length)); | |
System.out.println(new String(buffer, 0, n)); | |
} | |
int ni = System.in.available(); | |
if (ni > 0) { | |
int n = System.in.read(buffer, 0, Math.min(ni, buffer.length)); | |
in.write(buffer, 0, n); | |
in.flush(); | |
} | |
try { | |
Thread.sleep(10); | |
} | |
catch (InterruptedException e) { | |
} | |
} | |
System.out.println(process.exitValue()); | |
} | |
} |
It helped
This is what exactly I was looking for. Thanks 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dude, do you know how to get the handle to the external process and continuously read and write to it? . I am trying to communicate with a database client. I can establish a connection but could not write to it after the first read