1、Reader和Writer抽象类
字节流提供处理任何类型输入输出操作的足够功能,但不能直接操作Unicode字符,因而需要字符流。字符流层次结构的顶层是Reader和Writer抽象类,它们的顶层仍然是字节流。Reader是定义Java的流式字符输入模式的抽象类。Reader抽象类中的方法和InputStream类似。Writer是定义Java的流式字符输出模式的抽象类。该类的方法都返回void值并在出错条件下抛IOException异常。Writer抽象类中的方法和OutputStream类似。
2、FileReader和FileWriter
FileReader类表示可以读取文件内容的Reader类,构造方法有:
FileReader(String filePath)
FileReader(File fileObj)
FileWriter表示可以写文件的Writer类,构造方法有:
FileWriter(String filePath)
FileWriter(String filePath,boolean append)
FileWriter(File fileObj)
3、FileReader和FileWriter举例
package com.iotek.readerwriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReaderWriterDemo {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("f:\\hehe\\hehe.txt");
char[] buffer = new char[100];
FileWriter fWriter = new FileWriter("f:\\test\\hh.txt");
int len = 0;//实际读到的字符个数
while((len = fr.read(buffer))!=-1){
fWriter.write(buffer,0,len);
}
fr.close();
fWriter.close();
}
}
4、BufferedReader和BufferedWriter
BufferedReader通过缓冲区提高输入性能。BufferedWriter则通过缓冲区提高输出性能。类似于BufferedInputStream和BufferedOutputStream。分别都具有两个构造方法:
BufferedReader(Reader inputStream)
BufferedReader(Reader inputStream,int bufSize)
BufferedWriter(Writer ouputStream)
BufferedWriter(Writer outputStream,int bufSize)
5、BufferedReader和BufferedWriter举例
package com.iotek.readerwriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedReaderWriterDemo {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("f:\\hehe\\hehe.txt");
FileWriter fw = new FileWriter("f:\\test\\hh.txt");
BufferedReader bReader = new BufferedReader(fr);
BufferedWriter bWriter = new BufferedWriter(fw);
String line = null;
while((line=bReader.readLine())!=null){
System.out.println(line);
bWriter.write(line);//写入一行
bWriter.newLine();//换行
//bWriter.flush();//不使用close()方法时需要使用此方法
}
bReader.close();
bWriter.close();
}
}