从另一个java程序运行java程序 [英] Running a java program from another java program
问题描述
我正在研究一个简单的java程序。它只是编译并执行另一个java程序。我正在使用Runtime.exec()函数进行编译和运行。编译没有问题。但是当它运行时,如果第二个程序需要输入来从键盘读取,我不能从主进程中提供它。我使用了getOutputStream()函数。但它无济于事。我将提供我的代码。
I am working on a simple java program. It simply compiles and executes another java program. I am using Runtime.exec() function to compile and run. There is no problem with compilation. but when it runs, if the second program needs an input to read from keyboard, I can't give it from the master process. I used getOutputStream() function. but it couldn't help. I will provide my code.
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+"\n";
out.write(input.getBytes());
p.wait(10000);
out.flush();
}catch (IOException e) {
e.printStackTrace();
}
}
}
这是我的主程序( sam.java)。
This is my master program(sam.java).
以下是sam2.java的代码
The following is the code of 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..\n");
str = br.readLine();
System.out.println(Integer.parseInt(str));
}
}
没有问题,如果我的话第二个程序只有打印声明。但是当我不得不从另一个人那里读到东西时就会出现这个问题。
There is no problem, if my second program has only printing statements. But the problem arises when I have to read something from the other.
推荐答案
这有点奇怪但是你可以运行第二个程序没有分叉。只需调用其中的main方法即可。所以忘记运行时部分并执行以下操作:
It is a bit strange but you can run the second program without forking it. Just calling the main method in it. So forget the runtime section and do this:
sam2.main(new String[0]);
当然这样你必须在编译时编译sam2
Of course this way you must compile sam2 at compile time
这篇关于从另一个java程序运行java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!