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

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

 //对read()操作升级:使用read的重载方法
    @Test
    public  void testFileReader1()  {
        FileReader fr = null;

        try {
            //1.File类的实例化
            File file = new File("hello.txt");

            //2.FileReader类的实例化
            fr = new FileReader(file);

            //3。读入操作
            //方法一:
            //read(char[] cbuf):返回每次读入cbuf 数组中字符的个数。如果达到文件末尾返回-1
            char[] cbuf = new char[5];  //cbuf = char buffer
            int len;
            while((len = fr.read(cbuf)) != -1){
        //        for (int i = 0; i < len; i++) {     //错误写法 for(int i = 0; i < cbuf.length; i++)
        //            System.out.print(cbuf[i]);
        //        }
                //方法二:
                String str = new String(cbuf,0,len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr != null){
                //4.资源的关闭
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

版权声明:本文为weixin_55524604原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。