FileReader中使用read(char[] cbuf)读入数据

时间:2022-01-24
本文章向大家介绍FileReader中使用read(char[] cbuf)读入数据,主要包括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();
            }
        }
    }

原文地址:https://www.cnblogs.com/wshjyyysys/p/15840743.html