缓存读取文件的两种方式

本文展示了两种在Java中读取文件的方法:使用字节数组循环读取并扩容,以及利用StringBuffer逐块转换为字符串。第一种方式避免了预估文件大小的问题,而第二种则通过字符串拼接实现。两种方法最终都能得到相同的结果。



下面直接写代码,每次从文件中读取1M数据,循环读取

第一种方式


    public byte[]readByte(String filePaht) throws Exception{
         File file=new File(filePaht);
         BufferedInputStream binput=null;
         if(!file.exists())
             throw new Exception("sorry ,can not read unexists file");
         FileInputStream finput=new FileInputStream(file);
         binput=new BufferedInputStream(finput);
         binput=new BufferedInputStream(finput);
         byte[] temp=new byte[1024];
         byte[] result = new byte[1024];
         int t=0;
         int flit=0;
         while((t=binput.read(temp))!=-1){
             System.arraycopy(temp, 0, result, flit, t);
             flit=t;
             result=Arrays.copyOf(result, t+1024);
            
         }
    
        return result   
     }

第二种方式

    public void read(String filePaht) throws Exception{
         File file=new File(filePaht);
         BufferedInputStream binput=null;
         if(!file.exists())
             throw new Exception("sorry ,can not read unexists file");
         FileInputStream finput=new FileInputStream(file);
         binput=new BufferedInputStream(finput);
         byte[] temp=new byte[1024];
         StringBuffer sb=new StringBuffer();
         int tt=0;
         while( (tt=binput.read(temp))!=-1){
             sb.append(new String(temp,"GBK"));
         }
      
     }

说白了,第一种就是创建两个byte数组,一个临时数组,一个结果数组,然后不断的给结果数组扩容,避免在不知道文件具体大小时为起始容量发愁;第二种唯一不同在于通过StringBuffer绑定临时数组的数据,结果读出来肯定是一样的


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值