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

                                       

1)  java程序与其他进程的通信

package IO;

 

import java.io.*;

 

import sun.security.provider.SystemSigner;

public 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 {

           int count=0;

           InputStream ips=p.getInputStream();//获得输入流

           BufferedReader bfr=new BufferedReader(new InputStreamReader(ips));//包装输入流,按行读出

           while (true) {

              count++;

              if(count>50)

              {

                  break;

              }

              String strLine= bfr.readLine();//按行读取内存

              System.out.println(strLine);//打印输出行?

 

           }

          

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

    }

}

调用的进程

package IO;

import java.io.*;

public class MyTest {

 

    /**

     * @param args

     */

    public static void main(String[] args) throws Exception {

       // TODO Auto-generated method stub

       BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));    

       while (true) {

           //System.out.println("我来了");

           String strLine=bfr.readLine();

           if(strLine!=null)

           {

              System.out.println("hi:"+strLine);

           }

           else {

              return;

           }

       }

    }

 

}

问题分析:子进程不能执行

2)  把异常的字符串信息包装后发送出去

package IO;

import java.io.*;

public class TestPrintWriter {

 

 

    public static void main(String[] args) {

       try {

           throw new Exception("test");//抛出的异常

       } catch (Exception e) {

           StringWriter sw=new StringWriter();//声明字符串写入流

           PrintWriter pw=new PrintWriter(sw);//包装

           e.printStackTrace(pw);//输出异常流

           System.out.println(sw.toString());

           System.out.println(e.getMessage());

       }

 

    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值