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();

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值