字符流只能操作于纯文本的数据
一、输入流Reader
构造方法
protected FilterReader(Reader in)
创建一个新的 filtered reader。
Reader read=new FileReader("D:/test.txt");
方法:
abstract void close()
关闭该流并释放与之关联的所有资源。void mark(int readAheadLimit)
标记流中的当前位置。int read()
读取单个字符。int read(char[] cbuf)
将字符读入数组。abstract int read(char[] cbuf, int off, int len)
将字符读入数组的某一部分。int read(CharBuffer target)
试图将字符读入指定的字符缓冲区。boolean ready()
判断是否准备读取此流。void reset()
重置该流。long skip(long n)
跳过字符。
步骤
- 选择流
- 读入
- 关闭
实例
public static void main(String[] args) throws Exception {
//1.选择流
Reader read=new FileReader("D:/test01.txt");
//2.读入 写出
// int num=read.read(); 读取单个字符
//读取多个字符
char[] car=new char[1024];
int len=-1; //存储读取到数组中的数据个数
while((len=read.read(car))!=-1){
System.out.println(car);
}
//3.关闭
read.close();
}
三、输出流Writer
构造方法
FileWriter(String fileName)
根据给定的文件名构造一个 FileWriter 对象。
Writer write=new FileWriter("D:/test.txt");
FileWriter(String fileName, boolean append)
根据给定的文件名以及指示是否附加写入数据的 boolean 值来构造 FileWriter 对象。
Writer write=new FileWriter("D:/test.txt",true);
方法:
Writer append(char c)
将指定字符添加到此 writer。Writer append(CharSequence csq)
将指定字符序列添加到此 writer。Writer append(CharSequence csq, int start, int end)
将指定字符序列的子序列添加到此 writer.Appendable。abstract void close()
关闭此流,但要先刷新它。abstract void flush()
刷新该流的缓冲。void write(char[] cbuf)
写入字符数组。abstract void write(char[] cbuf, int off, int len)
写入字符数组的某一部分。- v
oid write(int c)
写入单个字符。 void write(String str)
写入字符串。void write(String str, int off, int len)
写入字符串的某一部分。
步骤
- 建立联系
- 创建流
- 写出
- 刷出
- 关闭
实例
public static void main(String[] args) throws IOException {
//1.选择流
Reader read=new FileReader("D:/test01.txt");
Writer write=new FileWriter("D:/test02.txt",true);
//2.读入 写出
// int num=read.read(); 读取单个字符
char[] car=new char[1024];
int len=-1; //存储读取到数组中的数据个数
while((len=read.read(car))!=-1){
write.write(car, 0, len);
}
//3.刷出
write.flush();
//4.关闭
write.close();
read.close();
}