问题
I'm trying to execute myfile.jar
using another java program which as follows. When the myfile.jar
is executed standalone in console, it will as two questions:
- Start the load process (y/n)?
- Start the patch process (y/n)?
I will pass y
to 1st and n
to 2nd question. The same thing I'm trying to do using the following java program and it successfully passes answer to the 1st question, but waiting at the 2nd question.
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();
Note: The myfile.jar
uses Scanner
to take the input from the user.
回答1:
I guess I found the solution to my question. For future reference, the following is the final program that I've used to solve my problem:
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();
来源:https://stackoverflow.com/questions/27687838/java-pass-values-to-the-jar-using-outputstreamwriter