Runtime对象的exec()方法可以运行平台上其它程序,该方法产生一个Process()对象代表子进程,Process类中就提供了进程通信的方法。
public class ReadFromTest { public static void main(String[] args) throws IOException { Process p = Runtime.getRuntime().exec("javac"); try (BufferedReader br = new BufferedReader(new InputStreamReader( p.getErrorStream()))) { String buff = null; while ((buff = br.readLine()) != null) { System.out.println(buff); } } } }
上述代码获取了javac进程的错误流,进行了打印。在下列代码中可以在Java程序中启动Java虚拟机运行另一个java程序,并向另一个程序中输入数据。
public class WriteToProcess { public static void main(String[] args) throws IOException { Process p = Runtime.getRuntime().exec("java ReadStandard"); try ( // 以p进程的输出流创建PrintStream,该输出流对本进程为输出流,对p进程则为输入流 PrintStream ps = new PrintStream(p.getOutputStream())) { ps.println("normal string"); ps.println(new WriteToProcess()); } } } class ReadStandard { public static void main(String[] args) throws FileNotFoundException { try (Scanner scan = new Scanner(System.in); PrintStream ps = new PrintStream( new FileOutputStream("out.txt"))) { scan.useDelimiter("\n"); while (scan.hasNext()) { ps.println("KeyBoards input:" + scan.next()); } } catch (IOException e) { e.printStackTrace(); } } }