Java:使用OutputStreamWriter将值传递给jar

时间:2014-12-29 11:19:09

标签: java outputstream

我尝试使用另一个java程序执行myfile.jar,如下所示。当myfile.jar在控制台中独立执行时,它将有两个问题:

  1. 开始加载过程(y / n)?
  2. 启动补丁程序(是/否)?
  3. 我会将y传递给第1和n到第2个问题。我尝试使用以下java程序做同样的事情,它成功地将答案传递给了第一个问题,但在第二个问题上等待。

    ProcessBuilder pb = new ProcessBuilder("java", "-jar", "myfile.jar", "arg1");
    pb.redirectErrorStream(true);
    
    Process p = pb.start();
    
    InputStream in = p.getInputStream();
    InputStreamReader ins = new InputStreamReader(in);
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream());
    BufferedReader br = new BufferedReader(ins);
    
    String line = null;
    
    out.write("y\n");
    out.write("n\n");
    out.flush();
    
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    
    out.close();
    p.waitFor();
    p.destroy();
    

    注意myfile.jar使用Scanner接收用户的输入。

1 个答案:

答案 0 :(得分:1)

我想我找到了问题的解决方案。以下是我用来解决问题的最终程序:

ProcessBuilder pb = new ProcessBuilder("java", "-jar", "myfile.jar", "arg1");
pb.redirectErrorStream(true);

Process p = pb.start();

InputStream in = p.getInputStream();
InputStreamReader ins = new InputStreamReader(in);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream());
BufferedReader br = new BufferedReader(ins);

String line = null;

while ((line = br.readLine()) != null) {
    System.out.println(line);

    if (line.contains("Start the load process (y/n)?")) {
        out.write("y");
        out.newLine();
        out.flush();
    }

    if (line.contains("Start the patch process (y/n)?")) {
        out.write("n");
        out.newLine();
        out.flush();
    }
}

out.close();
p.waitFor();
p.destroy();