【问题标题】:Handling interactive prompts in external process java处理外部进程java中的交互提示
【发布时间】:2019-03-16 01:05:53
【问题描述】:

我正在包装我经常与 GUI 界面一起使用的命令行应用程序。它基本上归结为执行它(作为 Java 进程),然后解析它的响应。但是,其中一个用例需要最终用户采取额外的行动(应用程序询问用户是否要覆盖文件),我不知道如何处理。一旦出现此提示,InputStream 和 ErrorStream 都会冻结。这是 executeCommand 方法的(非常通用的)代码:

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();
    }
}

我假设“文件已经存在。你想覆盖吗?[y/N]”提示正在通过其他渠道传递。我只是不知道如何处理它。对我来说理想的情况是,如果我可以用相同的问题提示 messageBox,然后相应地传递响应。

【问题讨论】:

标签: java process


【解决方案1】:

当你 fork 一个子进程时,它需要从父进程继承 I/O 才能与 stdinstdout 对话。使用 ProcessBuilder.inheritIO 在标准输入、标准输出和标准错误中重定向命令流。

【讨论】:

  • 感谢您的回答。但我仍然不确定如何手动将数据传递给子进程的标准输入。如果inheritIO方法将其直接复制到parentProcess stdout,我是否仍然能够逐行解析输出?我认为这可能是个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多