处理外部进程java中的交互式提示

问题描述 投票:0回答:1

我正在包装我常用于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个回答
1
投票

当你分支子进程时,它需要从父进程继承I / O来讨论stdinstdout。使用ProcessBuilder.inheritIO在stdin,stdout和stderr中重定向命令流。

© www.soinside.com 2019 - 2024. All rights reserved.