//对read()操作升级:使用read的重载方法
@Test
public void testFileReader1() throws IOException {
FileReader fr = null;
try {
//1. File类的实例化
File file = new File("hello.txt");
//2. FileReader流的实例化
fr = new FileReader(file);
//3. 读入的操作
//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1){
//方式一
//错误的写法
/*for (int i = 0; i < cbuf.length; i++) {
System.out.println(cbuf[i]);
}*/
//正确的写法
/*for (int i = 0; i < len; i++) {
System.out.println(cbuf[i]);
}*/
//方式二:
//错误的写法:对应着方式一的错误的写法
/*String str = new String(cbuf);
System.out.println(str);*/
//正确的写法
String str = new String(cbuf, 0 , len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.资源的关闭
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}