概述
java.io.FileReader类用于读取 文本文件 。构造时使用 UTF-8 和 默认字节缓冲区。
字符编码:字节与字符的对应规则。
Windows系统默认字符集是GBK。
unix、linux系统默认字符集是UTF-8。
idea等一些开发工具,默认编码集是UTF-8字节缓冲区:一个字节数组,用来临时存储字节数据。
构造方法
FileReader(File file): 创建一个新的 FileReader ,给定要读取的File对象。FileReader(String fileName): 创建一个新的 FileReader ,给定要读取的文件的名称。
必须传入一个文件路径
例子:
public class FileReaderConstructor throws IOException{
public static void main(String[] args) {
// 使用File对象创建流对象
File file = new File("a.txt");
FileReader fr = new FileReader(file);
// 使用文件名称创建流对象
FileReader fr = new FileReader("b.txt");
}
}
读取字符数据
读取一个字符
public int read() throws IOException
每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回-1
例子:
使用idea创建一个文本文件,内容是:java从入门到放弃,必须保持成UTF-8编码集
FileReader fr=new FileReader("test2.txt");
int i=0;
while((i=fr.read())!=-1) {
System.out.print((char)i);
}
fr.close();
输出结果:
java从入门到放弃
虽然读取了一个字符,但是会自动提升为int类型。
注意:
如果用GBK编码集保存,该类读取中文乱码
读取字符数组
public int read(char cbuf[], int offset, int length) throws IOException
创建一个长度是n的字符数组,每次读取n个字符到数组中
返回读取到的 有效字符个数,读取到末尾时,返回-1
例子:
FileReader fr=new FileReader("test2.txt");
char[] buf=new char[3];
int len=0;
while((len=fr.read(buf))!=-1) {
System.out.print(new String(buf));
}
fr.close();
输出结果:
java从入门到放弃到放
注意:
读取数据错误,末尾多了到放,是由于最后一次读取时,只读取一个字符弃,但数组中,上次读取的数据没有被完全替换,所以要通过len ,获取有效的字节
改动如下:
FileReader fr=new FileReader("test2.txt");
char[] buf=new char[2];
int len=0;
while((len=fr.read(buf))!=-1) {
System.out.print(new String(buf,0,len));
}
fr.close();