这个问题涉及两个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重定向有很好的了解,但遗憾的是我在该领域缺乏经验。提前谢谢大家。
德文
答案 0 :(得分:1)
替换它:
Process prog2 = rt.exec("java prog2");
有了这个:
Process prog2 = new ProcessBuilder("java", "prog2").inheritIO().start();
ProcessBuilder是Runtime.exec方法的首选替代品。