Java性能优化之组件-缓冲

缓冲区是一个特定的存储区域,可以协调应用程序上下层质量的性能差异,提高系统运行效率。缓冲最常使用的场景是I/O处理。JDK中提供了很多带缓冲的I/O组件。比如读取文件。

     public static void readByByte(String file ) {
       InputStreamis = null ;
        try {
           is = new FileInputStream( file); //按字节流读取
           int tmpByte;

            while ((tmpByte = is.read()) != -1) {
              System. out .println(tmpByte);
           }
       } catch (IOException e) {
            // do something...
       }
        if (is != null ){
            try {
              is.close();
           }
            catch (IOException e){
               // do something...
           }
            finally {
               // do something...
           }

       }

    }

该读取方式一次只能读取一个字节,适合读取二进制文件。如果想一次读取文本文件中的字符可以采用FileReader。

  public static void readByChar(Stringfile) {
     FileReader reader =null;
    try {
        reader =new FileReader(file);//按字符流读取
       int charCode;
       while ((charCode = reader.read()) != -1) {
          System.out.println((char) charCode);
        }
     }catch (IOException e) {
       // do something...
     }
      if (reader !=null) {
       try {
          reader.close();
        }catch (IOException e) {
         // do something...
        }finally {
         // do something...
        }
     }

   }

以上读取方式都只能一次读取一个字节数据,要读取整个文件就必须循环读取每一个字节,直到文件结束,效率较低,如果只是读取文本文件,此时可以采用BufferedReader,它采用缓冲的方式读取,一次可以读取一行。

       public static void readByLine(String file) {
     BufferedReader reader = null ;
     try {
        reader = new BufferedReader( new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null ) {
          System. out .println(line);
        }
     } catch (IOException e) {
        // do something...
     }
       if (reader !=null) {
        try {
          reader.close();
        } catch (IOException e) {
          // do something...
        } finally {
          // do something...
        }
     }

   }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值