这个问题与两个Java程序之间的输入和输出重定向有关。下面是我的问题的简化示例的源代码。
这是prog1:
import java.io.*;
public class prog1{
public static void main(String[] args) throws IOException{
Runtime rt = Runtime.getRuntime();
Process prog2 = rt.exec("java prog2");
System.out.println("prog2 has executed.");
}
}
在一个单独的文件中,我编写了prog2,在其中执行Internet Explorer以验证执行是否成功:
import java.io.*;
public class prog2{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string: ");
System.out.println("You entered " + in.readLine() + ". Starting Explorer...");
Runtime.getRuntime().exec("C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe");
}
}
这是我运行prog2的结果:
> java prog2
Enter a string: hello ** Here the program waited for my input **
You entered hello. Starting Explorer... ** Here Internet Explorer opens a new window **
这是我运行prog1所看到的:
> java prog1
prog2 has executed. ** Internet Explorer opens a new window **
请注意,prog2不会提示我输入,也没有输出任何内容。我的目标是实现以下目标:
> java prog1
Enter a string: hello ** Here I wish for the program to await my input **
You entered hello. Starting Explorer... ** Here I wish for an Explorer window to open **
prog2 has executed.
我相信此问题将需要对I / O重定向有充分的了解,但是很遗憾,我在该领域没有经验。谢谢大家。
德文
最佳答案
替换为:
Process prog2 = rt.exec("java prog2");
有了这个:
Process prog2 = new ProcessBuilder("java", "prog2").inheritIO().start();
ProcessBuilder是Runtime.exec方法的首选替代品。