上次我们学习了字符流读写——InputStreamReader和OutputStreamWriter,在使用这两个类进行字符型读取和写入时,首先要进行字节流和字符流的转换,即将FileInputStream和FileOutputStream转换为InputStreamReader和OutputStreamWriter。今天我们来看一个对字符流字符流更为简便的读取和写入方式:FileReader和FileWriter。
FileReader和FileWriter可以在不进行字节流和字符流转换的情况下,直接实现对文本文件的读写。我们通过一段简单的代码来测试一下:
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("D:\\log_network.txt");//没有直接声明编码方式
FileWriter fw=new FileWriter("D:\\FileWriter.txt");//直接写到一个文件里面去
char[] buf=new char[8*1024];
int c;
while((c=fr.read(buf, 0, buf.length))!=-1) {
fw.write(buf, 0, c);
fw.flush();
}
fr.close();
fw.close();
}
注意:FileReader和FileWriter不能指定编码方式,要想指定特定的编码方式,还是要回归到InputStreamReader和OutputStreamWriter上