java 程序与其它进程的数据通信

//Process类的实例对象来表示子进程。是以管道流的形式连接到父进程的一个输出流和输入流的对象上
//调用Process类的getOutputStream和getInputStream方法可获得连接子进程的输出流和输入流对象。

在TestInOut类启动java.exe执行另一个MyTest类。
TestInOut和MyTest通过进程间的管道相互传递数据。

 

 

DEMO:
import java.io.*;
class TestInOut implements Runnable{
    Process p=null;
    public TestInOut(){
        try{
                //要启动一个子进程
                p=Runtime.getRuntime().exec("java MyTest");//执行外部命令
                new Thread(this).start();//启动线程
        }catch(Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args){
        TestInOut tio=new TestInOut();
        tio.send();
    }

    //向子进程写数据
    public void send(){
        try{
            OutputStream ops=p.getOutputStream();//获取子进程的输出流,写入
            while(true){
                ops.write("help/r/n".getBytes());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
       
    //接收数据
    public void run(){
        try{
            InputStream in=p.getInputStream();//获取子进程的输入流,读取
            BufferedReader bfr=new BufferedReader(new InputStreamReader(in));//字节流转字符流
            while(true){
                String strLine=bfr.readLine();//读取一行
                if(strLine!=null)
                {
                    System.out.println(strLine);
                }else
                {
                    return ;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
   
     

 

import java.io.*;
class MyTest
{
 public static void main(String[] args) throws Exception
 {
  
  while(true){
   String strLine=new  BufferedReader(new InputStreamReader(System.in)).readLine();
   if(strLine!=null){
     System.out.println("hi:"+ strLine);//对应父进程的输出管道
      }else
   {
    return ;
   }
  }
  
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值