0

I'm wrapping command line application that I oftenly use with GUI interface. It basically comes down to executing it (as Java process) and then parsing its responses. However one of the usecases requires to take additional action by enduser (application asks if user wants to overwrite a file) and I'm not sure how to handle that. Both InputStream and ErrorStream freezes as soon as this prompt comes up. Here is a (pretty generic) code of executeCommand method:

private void executeCommand(String command) {

    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command("bash", "-c", command);
    try {

        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        String line = null;

        while ((line = reader.readLine()) != null) {
           //some actions "File already exists. Do you want to overwrite ? [y/N]" line never gets to this point
        }

        while ((line = errorReader.readLine()) != null) {
           //some actions "File already exists. Do you want to overwrite ? [y/N]" line never gets to this point
        }
        handleExitCode(process.waitFor(),"Success!");

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

I assume that "File already exists. Do you want to overwrite ? [y/N]" prompt is being passed through some other channel. I just don't know how to handle it. The ideal scenario for me would be if I could prompt messageBox with the same question and then pass the response accordingly.

JohnnyGat
  • 325
  • 2
  • 13
  • I suggest to use library https://github.com/remkop/picocli, or take a look at https://stackoverflow.com/questions/367706/how-do-i-parse-command-line-arguments-in-java. it would make your implementation easier to read and error-prone when reading command line input. – Holm Mar 15 '19 at 16:35

1 Answers1

1

When you are forking a child process, it needs to inherit I/O from parent process to talk stdin and stdout. Use ProcessBuilder.inheritIO to redirect your command streams in your stdin, stdout and stderr.

vavasthi
  • 922
  • 5
  • 14
  • Thank you for your answer. But I'm still not sure how to manually pass data to stdin of child process. Also would I still be able to parse the output line by line if inheritIO method would copy it directly to parentProcess stdout? I think that could be a problem – JohnnyGat Mar 17 '19 at 21:54