1

I'm executing some code on docker in my java application using ProcessBuilder to run the code, however i'm having trouble retrieving the output from it. BufferedReader is not reading anything from the InputStream returned from the container. Is there a specific way to retrieve output from Docker?? I've never had trouble getting output from bash executions before, so I'm thinking maybe docker does things differently somehow. Any ideas would be appreciated

Here's a snippet of the code:

    Process dockerCommand;
    ProcessBuilder builder = new ProcessBuilder("bash","-c","sudo docker images");
    builder.redirectErrorStream(true);
    builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    builder.redirectError(ProcessBuilder.Redirect.INHERIT);
    dockerCommand = builder.start();       

    dockerCommand.waitFor();

    List<String> result = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(dockerCommand.getInputStream()))
    {
        String line = reader.readLine();
        while (line != null) {
            result.add(line);
            line = reader.readLine();
        }
    } 
    catch (IOException exc) 
    {}
3
  • docker logs Commented Jan 31, 2017 at 11:51
  • Weird , I tried the provided code , and I was able to get the desired result. Where platform you are running it on , or are you sure the process which is running this program is sudo qualified. Commented Jan 31, 2017 at 11:56
  • @Rambler The code was created on Windows 10 x64. and compiled the jar in NetBeans IDE 8.2. I'm testing it on an Ubuntu machine which I'm connected to through puTTY. reader is returning with zero lines on my machine when executing "java -jar ... " However, the command is successfully executed and docker is loading the images in the console, but my strings where I'm attempting to store that output are empty after execution Commented Jan 31, 2017 at 12:52

1 Answer 1

1

The line

builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

causes bash to receive the same standard output as the parent process, which is presumably your terminal window. This produces misleading results because you actually see the Docker image list, but it's being printed by the shell.

If I comment that out and then iterate over the results list, I can see the output from Docker inside the JVM.

Sign up to request clarification or add additional context in comments.

1 Comment

You're absolutely correct. That fixed my problem. Thank you so much for the explanation.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.