字符流
目录
在顶层有Reader和Writer两个抽象类。Reader和Writer中定义了read()和write()方法,它们被派生流类重载
Reader抽象类的定义
public abstract class Reader implements Readable, Closeable {
//BIO,读取一个有效的字符,返回值为0到65535的整数,如果到达流的末尾则返回-1
public int read() throws IOException
//BIO,读取字符存储到char数组中,返回读取的字符个数,流结束则返回-1
public int read(char cbuf[]) throws IOException
//关闭流,同时释放资源
abstract public void close() throws IOException;
Writer抽象类的定义
public abstract class Writer implements Appendable, Closeable, Flushable {
//写出一个字符到字符流,要写的字符包含在给定整数值的16个低位;16个高位被忽略。
public void write(int c) throws IOException
//将字符数组中的指定部分内容压入到字符流,从off开始共len个字符
abstract public void write(char cbuf[], int off, int len) throws
IOException;
//关闭流,同时释放资源
abstract public void close() throws IOException;
相关的子类
- InputStreamReader、OutputStreamWriter桥接流,用于自动实现字节流和字符流的转换
- FileReader、FileWriter文件流,用于实现针对文本文件的读写操作
- CharArrayReader、CharArrayWriter内存流,用于实现针对char数组的读写操作
- PipedReader、PipedWriter管道流,用于线程之间的通讯
- FilterReader、FilterWriter过滤流的父类
- BufferedReader、BufferedWriter缓存流,用于在流中添加缓冲区
- StringReader、StringWriter内存流,用于实现针对字符串的读写操作
使用字符流实现txt文件的读取显示【其中包含中文】
编写一个程序,读取文件test.txt的内容并在控制台输出。如果源文件不存在,则显示相应的错误信息。
字符流Reader
- int read()读取一个字符并以整数的形式返回0-65535,如果返回-1则已到输入流末尾
- int read(char[] cbuf)读取一系列字符并存储到一个数组中,返回实际读取的字符数,如果读到输入 流末尾则返回-1
- void close()关闭输入流并释放内存资源
- int read(char[] cbuf, int off, int len) 读取len个字符并存储到一个数组中,从off位置开始,返回实 际读取的字符数,如果读取到输入流末尾则返回-1
- long skip(long n)跳过n个字符不读,返回实际跳过的字节数
字符流Writer
- void write(int c) 将字符(int数组的低8位)压入到字符流中
- void write(char[] cbuf, int off, int len)将字符数组中的指定部分内容压入到字符流中,从off开始共 len个字符
- void write(String str) 将字符串中的内容压入到字符流中 void close() 关闭流并释放所占用的资源
- void write(String str, int off, int len) 将字符串中的指定部分内容压入到字符流中,从下标off开始 共len个字符
- void flush()刷新缓冲区,将缓冲区中的数据全部送出到目标地,然后清空缓冲区
- void write(char[] cbuf) 将字符数组中的所有数据压入到字符流中
一般来说:一次读写一个字符效率太低,可以引入char[]数组提高执行效率