Home > Software engineering >  how to send stringed input into ProcessBuilder
how to send stringed input into ProcessBuilder

Time:10-15

class envir {
    public void run() throws IOException {
        ProcessBuilder builder = new ProcessBuilder("bash");
        builder.redirectInput(ProcessBuilder.Redirect.PIPE);
        builder.redirectOutput(ProcessBuilder.Redirect.PIPE);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        System.out.println(process.getInputStream());
    }
}

How do I make it so that I can send a string as input for my process builder to automate a cli (eg env python3) also using threads?

If you need more info please ask; I am bad at wording these questions.

CodePudding user response:

The names of the streams of Process are confusing. What you actually want is the output stream:

public abstract OutputStream getOutputStream()

Returns the output stream connected to the normal input of the subprocess.

So:

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8));

Then write to it:

bw.write("Your string");
bw.newLine();
  • Related