0
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.

7
  • not sure what are you asking, but on other topic, "builder" is a fluent API so you can use it like a "stream" without calling "builder" each line. Commented Oct 14, 2021 at 13:19
  • Get a Writer, e.g. new BufferedWriter(new OutputStreamWriter(process.getInputStream())), and write into it. Commented Oct 14, 2021 at 13:20
  • How do you do it though? Commented Oct 14, 2021 at 13:20
  • builder.redirectInput(ProcessBuilder.Redirect.PIPE) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectErrorStream(true); Commented Oct 14, 2021 at 13:21
  • @AndyTurner can you please explain further Commented Oct 14, 2021 at 13:24

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

10 Comments

The important misconception that this answer corrects is this: getInputStream() creates an InputStream that you use to read the standard output of the subprocess. getOutputStream writes to the process stdin. Think: out of the subprocess INTO the parent process and into the subprocess OUT OF the parent process.
@kutschkem or, if you can't remember, read the doc :)
doesn't seem to execute command
@LaithStriegher The newLine is important, do you have that too?
Or bw.flush(), alternatively/additionally.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.