我尝试使用另一个java程序执行myfile.jar
,如下所示。当myfile.jar
在控制台中独立执行时,它将有两个问题:
我会将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
接收用户的输入。
答案 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();