Skip to content

Instantly share code, notes, and snippets.

@thangdc94
Created December 15, 2017 11:15
Show Gist options
  • Save thangdc94/80c915bccb85027965d0d4376b6a0a74 to your computer and use it in GitHub Desktop.
Save thangdc94/80c915bccb85027965d0d4376b6a0a74 to your computer and use it in GitHub Desktop.
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
/**
* Created by thangpn7 on 12/15/2017
*/
public class ScriptExecutor {
private Logger logger = Logger.getLogger(ScriptExecutor.class);
private PrintWriter writer;
public ScriptExecutor() throws IOException {
Process process = Runtime.getRuntime().exec("cmd");
OutputStream pStdin = process.getOutputStream(); // <- Eh? write to this
redirectProcessOutputs(process);
writer = new PrintWriter(pStdin);
}
private void redirectProcessOutputs(Process process) {
InputStream pStdout = process.getInputStream();
InputStream pStderr = process.getErrorStream();
Thread errorPipe = new Thread(new SyncPipe(pStderr, System.err));
errorPipe.start();
Thread outputPipe = new Thread(new SyncPipe(pStdout, System.out));
outputPipe.start();
}
public void executeCmd(String... commands) throws IOException {
logger.debug("Executing " + Arrays.toString(commands));
for (String cmd : commands) {
writer.println(cmd);
writer.flush();
}
}
public void close() throws IOException {
writer.println("exit");
writer.flush();
}
}
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by thangpn7 on 12/15/2017
*/
public class SyncPipe implements Runnable {
private final OutputStream out;
private final InputStream in;
public SyncPipe(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
@Override
public void run() {
try {
final byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment