Java虚拟机读写其他进程的数据
使用Runtime对象的exec()方法可以获得其他进程的Process对象,Process对象代表由该Java程序启动的子进程,Process类提供了如下3个方法,用于让程序和其子进程进行通讯。
InputStream getErrorStream():获取子进程的错误流
InputStream getInputStream():获取子进程的输入流
OutputStream getOutputStream():获取子进程的输出流
下面的代码实现了获取子进程的错误输出
import java.io.BufferedReader;import java.io.InputStreamReader;public class Test {public static void main(String[] args) throws Exception{Process p=Runtime.getRuntime().exec("adb");BufferedReader br=new BufferedReader(new InputStreamReader(p.getErrorStream()));String str=null;while((str=br.readLine())!=null){System.out.println(str);}}}下面程序演示两个Java程序通讯
这个数父进程
import java.io.OutputStream;import java.io.PrintStream;public class Test {public static void main(String[] args) throws Exception{Process p=Runtime.getRuntime().exec("java work");OutputStream os=p.getOutputStream();PrintStream ps=new PrintStream(os);ps.println("张译成");os.close();}}
下面是子进程
import java.io.FileOutputStream;import java.io.PrintStream;import java.util.Scanner;public class work {public static void main(String[] args) throws Exception{Scanner sc=new Scanner(System.in);FileOutputStream fis=new FileOutputStream("work");PrintStream ps=new PrintStream(fis);System.setOut(ps);while(sc.hasNextLine()){System.out.println(sc.nextLine());}ps.close();}}