//对read()操作升级:使用read的重载方法
@Test
public void testFileReader1(){
FileReader fr = null;
try {
//1.File类的实例化
File file = new File("he.txt");
//2.FileReader流的实例化
fr = new FileReader(file);
//3.读入的操作
//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数 如果达到文件末尾 返回-1
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.print(cbuf[i]);
// }
//方式二:
//错误的写法,对应着方式一的错误情况
// String str = new String(cbuf);
// System.out.print(str);
//正确的写法
String str = new String(cbuf,0,len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源的关闭
if (fr != null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
[IO流]FileReader中使用read(char[] cbuf)读入数据
最新推荐文章于 2024-05-13 09:40:30 发布