FileReader:用来读取字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的。要自己指定这些值,可以先在 FileInputStream 上构造一个 InputStreamReader。
FileReader
用于读取字符流。要读取原始字节流,请考虑使用FileInputStream
。
第一步: 创建字符流对象 怎么创建?? ==》 通过FileReader的构造方法创建
构造方法摘要 FileReader(File file)
在给定从中读取数据的 File 的情况下创建一个新 FileReader。FileReader(FileDescriptor fd)
在给定从中读取数据的 FileDescriptor 的情况下创建一个新 FileReader。FileReader(String fileName)
在给定从中读取数据的文件名的情况下创建一个新 FileReader。
第二步:读取文件内容 怎么读取?? ==》 通过字符流的
read方法(从类 java.io.InputStreamReader 继承的方法)
public int read():读取单个字符。
返回:读取的字符,如果已到达流的末尾,则返回 -1
public int read(char[] cbuf, int offset, int length) throws IOException:将字符读入数组中的某一部分。
参数:
cbuf
- 目标缓冲区
offset
- 从其处开始存储字符的偏移量
length
- 要读取的最大字符数返回:读取的字符数,如果已到达流的末尾,则返回 -1
第三步:关闭流
ex:
/*** 字符流-文件输入流FileReader:* 要求:读取 文本 (注意:只用来读取文本,不读取音频、视频、图片)* 1.创建字符流对象 怎么创建?? ==》 通过FileReader的构造方法创建* ①:FileReader(File file) :在给定从中读取数据的 File 的情况下创建一个新 FileReader。 * ②:FileReader(FileDescriptor fd) :在给定从中读取数据的 FileDescriptor 的情况下创建一个新 FileReader。 * ③:FileReader(String fileName) :在给定从中读取数据的文件名的情况下创建一个新 FileReader。 * 2.读取文件内容 怎么读取?? ==》 通过字符流的read方法(从类 java.io.InputStreamReader 继承的方法)* ①:public int read():读取单个字符。* ②:public int read(char[] cbuf, int offset, int length) throws IOException:将字符读入数组中的某一部分。* 3.关闭流* @author 郑清*/
public class Demo {public static void main(String[] args) throws IOException {//1.创建字符流对象FileReader fr = new FileReader("D:1/1.txt");//2.读取内容://方式①:public int read():读取单个字符。int read = fr.read();//读取第一个字符while(read != -1) {System.out.print((char)read);read = fr.read();//当未读取到文件末尾时 继续读取下1个字符}//方式②:public int read(char[] cbuf, int offset, int length) throws IOException:将字符读入数组中的某一部分。char[] c = new char[10];int length;//保存每次读取了多少个字符while((length = fr.read(c)) != -1) {System.out.print(new String(c, 0, length));//String(byte[] bytes, int offset, int length):通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。}//3.关闭流fr.close();}}