FileReader中使用read(char[] cbuf)读入数据
//对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();
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步