Java性能优化之组件-缓冲

来源:互联网 发布:中国银联和银联数据 编辑:程序博客网 时间:2024/04/29 07:33

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

    publicstaticvoid readByByte(Stringfile) {
       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
原创粉丝点击