You need to drain those streams in two dedicated threats - or in some cases use the redirect feature to pipe it to the stdout of the parent (good option for automation scripting)

I think without a helper ProcessBuilder is hard to use for such cases 

From: core-libs-dev <core-libs-dev-r...@openjdk.org> on behalf of Cay Horstmann <cay.horstm...@gmail.com>
Sent: Tuesday, April 15, 2025 8:53 AM
To: Ron Pressler <ron.press...@oracle.com>; Remi Forax <fo...@univ-mlv.fr>
Cc: core-libs-dev <core-libs-dev@openjdk.org>; David Alayachew <davidalayac...@gmail.com>
Subject: Re: [External] : Re: My experience using Java to do CLI Scripting
 


Il 14/04/25 23:46, Ron Pressler ha scritto:
>
>
>> On 14 Apr 2025, at 21:48, Remi Forax <fo...@univ-mlv.fr> wrote:
>>
>>
>> Hi Ron,
>> i think you need to close the inputReader
>>
>> public static String output(String... args) {
>> ProcessBuilder processBuilder = new ProcessBuilder(args);
>> try {
>> Process process = processBuilder.start();
>> try (BufferedReader reader = process.inputReader()) {
>> return reader.lines().collect(Collectors.joining("\n"));
>> }
>> } catch (IOException e) {
>> throw new IOError(e);
>> }
>> }
>
>
> When the process terminates, the InputStream underlying the pipe is closed (after being drained and the unread bytes served by a ByteArrayInputStream), which *I think* should be sufficient, but I could be wrong.
>
> — Ron

Reading the process output into a string or string stream raises a number of worries.

* Do I need to wait for the process to complete?
* Do I need to close anything?
* How exactly do I use getInputStream()/inputReader() with *extreme care*, as the API doc warns me?

If it is safe to call

builder.start().inputReader().lines()

or

builder.start().getInputStream().readAllBytes()

without waiting or closing, then the API doc could say so. If not, then maybe a safe method to get the entire output would be appropriate for Process?


--

Cay S. Horstmann | https://horstmann.com

 

Reply via email to