• Java基础IO类之缓冲流


    首先要明确一个概念:

      对文件或其他目标频繁的读写操作,效率低,性能差。

      使用缓冲流的好处是:能够高效的读写信息,原理是先将数据先缓冲起来,然后一起写入或者读取出来。

    对于字节:

    BufferedInputStream:为另一个输入流添加一些功能,在创建BufferedInputStream时,会创建一个内部缓冲区数组,用于缓冲数据。

    BufferedOutputStream:通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必针对每次字节写入调用底层系统。

    对于字符:

    BufferedReader:将字符输入流中读取文本,并缓冲各个字符,从而实现字符、数组、和行的高效读取。

    BufferedWriter:将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。

    代码示例:

    package IODemo;
    
    import java.io.*;
    /*
    缓冲的目的:
    解决在写入文件操作时,频繁的操作文件所带来的性能降低的问题
    BufferedOutStream 内部默认的缓冲大小是 8Kb,每次写入储存到缓存中的byte数组中,当数组存满是,会把数组中的数据写入文件
    并且缓存下标归零
     */
    public class BufferedDemo {
    
        //使用新语法 会在try里面帮关掉这个流
        private static void BuffRead2(){
            File file = new File("d:\test\t.txt");
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){
    
                byte[] bytes = new byte[1024];
                int len = -1;
                while ((len = bis.read(bytes))!=-1){
                    System.out.println(new String(bytes,0,len));
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        private static void BuffRead(){
            File file = new File("d:\test\t.txt");
            try {
                InputStream in = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(in);
                byte[] bytes = new byte[1024];
                int len = -1;
                while ((len = bis.read(bytes))!=-1){
                    System.out.println(new String(bytes,0,len));
                }
                bis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    
        private static void BuffWrite(){
            File file = new File("d:\test\t.txt");
            try {
                OutputStream out = new FileOutputStream(file);
                //构造一个字节缓冲流
                BufferedOutputStream  bos = new BufferedOutputStream(out);
                String info = "我是落魄书生";
    
                bos.write(info.getBytes());
                bos.close();
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
        public static void main(String[] args) {
      //  BuffWrite();
            BuffRead2();
        }
    }
  • 相关阅读:
    大型网站应用之海量数据和高并发解决方案总结
    反转二叉树
    Spring bean循环依赖
    死磕Spring AOP (学习持续更新中。。)
    Context 初始化流程
    ConcurrentHashMap
    2-MySQL高级-事务-基本概念(1)
    1-MySQL高级-视图
    11-python基础—格式化的两种方式
    22-MySQL-Ubuntu-备份与恢复
  • 原文地址:https://www.cnblogs.com/lpss-75074038/p/11974024.html
Copyright © 2020-2023  润新知