简体   繁体   中英

Piping a string into Java Runtime.exec() as input

I have a string that I need to pipe into an external program, then read the output back. I understand how to read the output back, but how do I pipe this string as input? Thanks!

It goes like this (uncompiled and untested)

Process p = Runtime . getRuntime ( ) . exec ( ... ) ;
Writer w = new java . io . OutputStreamWriter ( p . getOutputStream ( ) ) ;
w . append ( yourString ) ;
w. flush ( ) ;
// read the input back

Careful that you don't create a deadlock. Reading/writing to the process in the same thread can be problematic if the process is writing data you are not reading and meanwhile you are writing data it is not reading.

I tend to use a little pattern line this to get the io going in different threads:

import java.io.InputStream;
import java.io.OutputStream;

public final class Pipe implements Runnable {

    private final InputStream in;
    private final OutputStream out;

    public Pipe(InputStream in, OutputStream out) {
        this.in = in;
        this.out = out;
    }

    public static void pipe(Process process) {
        pipe(process.getInputStream(), System.out);
        pipe(process.getErrorStream(), System.err);
        pipe(System.in, process.getOutputStream());
    }

    public static void pipe(InputStream in, OutputStream out) {
        final Thread thread = new Thread(new Pipe(in, out));
        thread.setDaemon(true);
        thread.start();
    }

    public void run() {
        try {
            int i = -1;

            byte[] buf = new byte[1024];

            while ((i = in.read(buf)) != -1) {
                out.write(buf, 0, i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This may or may not apply to what you want to do -- maybe your dealing with an established set of input that is guaranteed to show up after certain expected output (or vice versa, or several iterations of that). Ie some synchronous block and step kind of interaction.

But if you are simply 'watching' for something that might show up then this is a good start in the right direction. You would pass in some different streams and work in some java.util.concurrent 'await(long,TimeUnit)' type code for waiting for the response. Java IO blocks basically forever on read() ops, so separating yourself from those threads will allow you to give up after a certain time if you don't get the expected response from the external process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM