PipedInputStream与PipedOutputStream类 ByteArrayInputStream与ByteArrayOutputStream类 2011-4-22

PipedInputStream与PipedOutputStream类用于在应用程序中的创建管道通信
 主要用于完成线程间的通信
 管道要能通信必须要建立连接connect
 public class Sender extends Thread
 {
   private PipedOutputStream out = new PipedOutputStream();
   public PipedOutputStream getOutputStream()
 {
  return out;
 }
   public void run()
 {
  String strInfo = new String("hello,receiver!");
 try
  {
  out.write(strInfo.getBytes());
  out.close();
  }
 catch(Exception e)
  {
  e.printStackTrace();
  }
 }
 }


 public class Receiver extends Thread
 {
   private PipedInputStream in = new PipedInputStream();
   public PipedInputStream getInputStream()
 {
  return in;
 }
   public void run()
 {
  bytep[] buf = new byte[1024];
 try
  {
  int len = in.read(buf);
  System.out.println("the following message comes from sender:/n" + new String(buf,0,len));
  out.close();
  }
 catch(Exception e)
  {
  e.printStackTrace();
  }
 }
 }

 public static void main(String[] args) throws Exception
 {
 Sender t1 = new Sender();
 Receiver t2 = new Receiver();
 
 PipedOutputStream out = t1.getOutputStream();
 PipedInputStream in = t2.getInputStream();
 out.connect(in);
 t1.start();
 t2.start();
 }

PipedWriter和PipedReader类
 使用管道流类,可以实现各个程序模块之间的松耦合通信。
 使用管道流,有利于模块化

ByteArrayInputStream与ByteArrayOutputStream类
 ByteArrayInputStream与ByteArrayOutputStream,用于以IO流的方式来完成对字节数组内容
 的读写,来支持类似内存虚拟文件或者内存映像文件的功能。
 ByteArrayInputStream的两个构造函数
 -ByteArrayInputStream(byte[] buf)
 -ByteArrayInputStream(byte[] buf,int offset,int length)
 ByteArrayOutputStream
 -ByteArrayOutputStream() //创建32个字节的缓冲区,数据过大或自动增长
 -ByteArrayOutputStream(int)//创建指定大小的缓冲区,数据过大或自动增长

 public static void main(String[] args)
 {
 String tmp = "abcde";
 byte[] src = tmp.getBytes();
 ByteArrayInputStream input = new ByteArrayInputStream(src);
 ByteArrayOutputStream output = new ByteArrayOutputStream();
 transform(input,output);
 byte[] result = output.toByteArray();
 System.out.println(new String(result));
 transform(System.in,System.out);//复用性,读取键盘输入然后从屏幕输出
 }
 public static void transform(InputStream in,OutputStream out)
 {
  int ch = 0;
 try
 {
  while(ch = in.read() != -1)
  {

   int upperCh = /*(int)*/Character.toUpperCase( (char)ch );
    out.write(upperCh);
   }
  }
  catch(Exception e)
  {
    e.printStackTrace();
  }
 }

StringReader和StringWriter类来以字符IO流的方式处理字符串

重视IO程序代码的复用
 -System.in连接到键盘,是InputStream类型的实例对象。
 -System.out连接到显示器,是PrintStream类的实例对象。
 -不管各种底层物理设备用什么方式实现数据的终止点,InputStream的
  read方式总是返回-1来表示输入流的结束。
 -在Windows下,按下Ctrl+Z组合键可以产生键盘输入流的结束标记,在
  Linux下,则是按下Ctrl+D组合键来产生键盘输入流的结束标记。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值