java.io.FileReader
类是读取字符文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。
-
字符编码:字节与字符的对应规则。Windows系统的中文编码默认是GBK编码表。
-
字节缓冲区:一个字节数组,用来临时存储字节数据。
构造方法
当你创建一个流对象时,必须传入一个文件路径。类似于FileInputStream
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");
}
}
读取字符数据
1. 读取字符
read()
:读取一个字符的数据,提升为int类型,读取到文件末尾,返回-1
,循环读取
注意
虽然读取了一个字符,但是会自动提升为int类型。
代码演示:
public class FRRead {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileReader fr = new FileReader("read.txt");
// 定义变量,保存数据
int b ;
// 循环读取
while ((b = fr.read())!=-1) {
System.out.println((char)b);
}
// 关闭资源
fr.close();
}
}
结果:
钢
铁
侠
浩
克
2. 使用字符数组读取
read(char[] cbuf)
:每次读取b的长度个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回-1
代码演示:
public class FRRead {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileReader fr = new FileReader("read.txt");
// 定义变量,保存有效字符个数
int len ;
// 定义字符数组,作为装字符数据的容器
char[] cbuf = new char[2];
// 循环读取
while ((len = fr.read(cbuf))!=-1) {
System.out.println(new String(cbuf));
}
// 关闭资源
fr.close();
}
}
结果:
钢铁
侠浩
克浩
获取有效的字符改进,代码使用演示:
public class FISRead {
public static void main(String[] args) throws IOException {
// 使用文件名称创建流对象
FileReader fr = new FileReader("read.txt");
// 定义变量,保存有效字符个数
int len ;
// 定义字符数组,作为装字符数据的容器
char[] cs = new char[2];
// 循环读取
while ((len = fr.read(cs))!=-1) {
System.out.println(new String(cs,0,len));
}
// 关闭资源
fr.close();
}
}
结果:
钢铁
侠浩
克