通过 Java 进程将输入发送到 运行 JAR
Sending input to a running JAR via Java process
我想编写一个程序来执行 JAR 并获取它们的输出。
当 JAR 程序只有一个打印语句时,它可以正常工作,但是当它在执行过程中要求输入时,程序会卡住。
JAR文件程序代码:
import java.util.*;
public class demo {
public static void main(String r[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Hello ...");
System.out.println("please enter the number :");
int i = sc.nextInt();
System.out.println(" number : " + i);
}
}
运行JAR文件的原程序代码:
public class jartorun {
public static void main(String arg[]) throws IOException {
String t = "javaw -jar D:\jarcheck\temp.jar";
Process p = Runtime.getRuntime().exec(t);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.print(line + "\n");
}
input.close();
}
}
我可以使用 process.getOutputStream()
向 JAR 提供输入,但我该如何使用它才能创建一个程序,向 JAR 提供输入并同时读取其输出?
您可以使用 p.getOutputStream()
为启动的进程提供输入。
如果你想 运行 虚拟机之外的东西使用 ProcessBuilder
。对我来说很好用,你可以继承 IO Stream。
ProcessBuilder builder = new ProcessBuilder("./script.sh",
"parameter1");
builder.directory(new File("/home/user/scripts/"));
builder.inheritIO();
try {
Process p = builder.start();
p.waitFor();
// Wait for to finish
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
这也适用于 Windows 批处理脚本和路径。
(虽然还没有尝试输入)
我想编写一个程序来执行 JAR 并获取它们的输出。 当 JAR 程序只有一个打印语句时,它可以正常工作,但是当它在执行过程中要求输入时,程序会卡住。
JAR文件程序代码:
import java.util.*;
public class demo {
public static void main(String r[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Hello ...");
System.out.println("please enter the number :");
int i = sc.nextInt();
System.out.println(" number : " + i);
}
}
运行JAR文件的原程序代码:
public class jartorun {
public static void main(String arg[]) throws IOException {
String t = "javaw -jar D:\jarcheck\temp.jar";
Process p = Runtime.getRuntime().exec(t);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.print(line + "\n");
}
input.close();
}
}
我可以使用 process.getOutputStream()
向 JAR 提供输入,但我该如何使用它才能创建一个程序,向 JAR 提供输入并同时读取其输出?
您可以使用 p.getOutputStream()
为启动的进程提供输入。
如果你想 运行 虚拟机之外的东西使用 ProcessBuilder
。对我来说很好用,你可以继承 IO Stream。
ProcessBuilder builder = new ProcessBuilder("./script.sh",
"parameter1");
builder.directory(new File("/home/user/scripts/"));
builder.inheritIO();
try {
Process p = builder.start();
p.waitFor();
// Wait for to finish
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
这也适用于 Windows 批处理脚本和路径。 (虽然还没有尝试输入)