Java: Pass values to the jar using OutputStreamWriter

穿精又带淫゛_ 提交于 2019-12-12 02:27:00

问题


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:

  1. Start the load process (y/n)?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!