我正在研究一个简单的java程序.它只是编译并执行另一个java程序.我正在使用Runtime.exec()函数进行编译和运行.编译没有问题.但是当它运行时,如果第二个程序需要输入来从键盘读取,我不能从主进程中提供它.我使用了getOutputStream()函数.但它无能为力.我会提供我的代码.
public class sam {
public static void main(String[] args) throws Exception {
try {
Process p = Runtime.getRuntime().exec("javac sam2.java");
Process p2 = Runtime.getRuntime().exec("java sam2");
BufferedReader in = new BufferedReader(
new InputStreamReader(p2.getInputStream()));
OutputStream out = p.getOutputStream();
String line = null;
line = in.readLine();
System.out.println(line);
input=input+"
";
out.write(input.getBytes());
p.wait(10000);
out.flush();
}catch (IOException e) {
e.printStackTrace();
}
}
}
这是我的主程序(sam.java).
以下是sam2.java的代码
public class sam2 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter the number..
");
str = br.readLine();
System.out.println(Integer.parseInt(str));
}
}
如果我的第二个程序只有打印语句,那就没问题了.但是当我必须从另一个人那里读到一些东西时,问题就出现了.