Skip to content

Instantly share code, notes, and snippets.

@pditommaso
Created March 31, 2012 14:26
Show Gist options
  • Save pditommaso/2265496 to your computer and use it in GitHub Desktop.
Save pditommaso/2265496 to your computer and use it in GitHub Desktop.
Read/write input/output stream of interactive process
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());
}
}
@pditommaso
Copy link
Author

@dinesh-papineni
Copy link

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

@sampleref
Copy link

It helped

@mohammedmustafa2348
Copy link

mohammedmustafa2348 commented Mar 15, 2018

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