一、首先找到Reader类下的子类FileReader():
二、选取构造方法
三、有两种方法:
(一)、read( )
(二)、read(char[ ] ch,int offset,int length)
(一)、先看第一种:
1、编写代码
/**
* @author James
* @create 2019-12-31 16:15
*
* //需求:读取一个文本文件。将读取到的字符打印到控制台。
*/
public class FileReaderDemo {
public static void main(String[] args) throws IOException {
//绑定读取的文件
FileReader fr = new FileReader("demo.txt");
//初始化返回值
int ch = 0;
// 循环读取
while ((ch = fr.read()) !=-1){
System.out.println((char) ch);
}
}
2、结果:
(二)、第二种 read(char[ ] ch,int offset,int length)
代码示例一:
public static void main(String[] args) throws IOException {
/**
* 使用read(char[]) 读取文本数据
*/
//创建读取流
FileReader fr = new FileReader("demo.txt");
//创建数组
char[] ch = new char[3];
//初始化返回值
int num = fr.read(ch);
System.out.println(num+":"+new String(ch,0,num));
int num2 = fr.read(ch);
System.out.println(num2+":"+new String(ch,0,num2));
int num3 = fr.read(ch);
System.out.println(num3+":"+new String(ch,0,num3));
}
结果:
画图演示:
简化后的代码:
public static void main(String[] args) throws IOException {
/**
* 使用read(char[]) 读取文本数据
*/
//创建读取流
FileReader fr = new FileReader("demo.txt");
//创建数组
char[] ch = new char[3];
//初始化返回值
int len=0;
while ((len=fr.read(ch))!=-1){
System.out.println(new String(ch,0,len));
}
}
read() 和read(char[ ] ,int offset, int length)的区别:
read( )是读取单个字符,所以要读很多次。
read(char[ ] ,int offset, int length) 读取一组字符文件。
所以在效率上 read(char[ ] ,int offset, int length)强于read( )。