lesson6.6PipedInputStream和ByteArrayInputStream类

来源:互联网 发布:头皮里面长痘痘 知乎 编辑:程序博客网 时间:2024/05/29 17:26

PipedInputStream类和PipedOutputStream类用于创造管道通信,两者连接产生管道,前者从管道中读取数据,后者向管道中写入数据,通常用于完成线程之间的通信。

常用函数可以查看帮助文档,这里主要巨鹿使用管道完成线程通信的方法:

两个线程类中定义自己的管道对象,并且定义一个可以返回管道对象的方法,在run函数中完成通信内容,在外部使用时得到两个线程中的管道对象,连接(connect)即可,开始两个线程就会自动实现通信。

习题:两个线程实现发送一条信息

import java.io.*;public class TestPipedInputStream {public static void main(String[] args){Sender s = new Sender();Receiver r = new Receiver();PipedOutputStream out = s.output;//得到两个线程中的管道对象PipedInputStream in = r.input;try{in.connect(out);//连接}catch(Exception e){e.printStackTrace();}s.start();r.start();}}class Sender extends Thread{PipedOutputStream output = new PipedOutputStream();PipedOutputStream getInput(){return output;}public void run(){String s = new String("This is for test");try{output.write(s.getBytes());//向管道中写入信息output.close();}catch(Exception e){e.printStackTrace();}}}class Receiver extends Thread{PipedInputStream input = new PipedInputStream();PipedInputStream getInput(){return input;}public void run(){int len = 0;byte[] b = new byte[1024];try{len = input.read(b);//从管道中读出信息input.close();}catch(Exception e){e.printStackTrace();}System.out.println(new String(b,0,len));//打印}}


ByteArrayInputStream类和ByteArrayOutputStream类

用于以IO流的方式完成字节数组的读写,通常用来实现类似内存虚拟文件和内存映像文件的功能。

程序在运行过程中产生的临时文件采用内存虚拟文件就可以不用访问硬盘会极大的提高效率。通常将两个类的实例对象作为参数传递给处理函数。

习题:将一串字符串转换为大写输出

import java.io.*;public class TestByteArrayInputStream {public static void main(String[] args){String s = new String("asdFRsdfTGgh");ByteArrayInputStream bInput = new ByteArrayInputStream(s.getBytes());//ByteArrayOutputStream bOutput = new ByteArrayOutputStream();//transform(bInput, bOutput);System.out.println(bOutput.toString());}//定义一个函数将小写字母改为大写字母public static void transform(InputStream input, OutputStream output){int ch = 0;try{while((ch = input.read())!= -1)//读出单个字符转换成大写{int ch1 = Character.toUpperCase((char)ch);output.write(ch1);//写入输出流}}catch(Exception e){e.printStackTrace();}}}

总结:PipedInputSream, ByteArrayInputStream,以及上一节的FileInputStream类都是InputSteam的子类,都拥有读的方法read,都是从输入流中读取字节;PipedOutputStream, ByteArrayOutputStream, FileOutputSteam都是Output的子类,都有写write的方法,都是向输出流中写入字节数组,在用的时候只要记住Input是读,output是写就分清了。

另外这三对流类都有针对字符的类分别是PipedWriter,PipedReader和StringWriter,StringReader和FileWriter,FileReader。


阅读全文
0 0
原创粉丝点击