转自:
Java IO包中字符流Piped和CharArray简介说明
下文讲述java中管道与字符数组的读写简介,如:PipedReader、PipedWriter、CharArrayReader、CharArrayWriter
PipedReader的功能:
从管道中读取字符流
其功能同PipedInputStream相似,
PipedReader同PipedInputStream的区别: PipedReader读取的数据为字符 PipedInputStream读取的数据为字节
例:
Reader reader = new PipedReader(pipedWriter); int data = reader.read(); while(data != -1) { doSomethingWithData(data); data = reader.read(); } reader.close();
PipedWriter的功能:
向管道中写入字符流
PipedWriter同PipedOutputStream的区别: PipedWriter输出的数据为字符 PipedOutputStream输出的数据为字节
例:
PipedWriter writer = new PipedWriter(pipedReader); while(moreData()) { int data = getMoreData(); writer.write(data); } writer.close();
CharArrayReader的功能:
从字符数组中读取字符流,如下所示:
char[] chars = ... //获取字符数组 Reader reader = new CharArrayReader(chars); int data = reader.read(); while(data != -1) { //数据读取 data = reader.read(); } reader.close();
当数据是字符数组,此时CharArrayReader可以非常容易的获取你所想要的数据
CharArrayReader会包含一个字符数组,然后将字符数组转换成字符流
CharArrayWriter的功能:
将字符数组写入到字符输出流writer中,如下所示:
CharArrayWriter writer = new CharArrayWriter(); char[] chars = writer.toCharArray();