缓存流

以介质是硬盘为例,字节流和字符流的弊端:
在每一次读写的时候,都会访问硬盘。 如果读写的频率比较高的时候,其性能表现不佳。

为了解决以上弊端,采用缓存流。
缓存流在读取的时候,会一次性读较多的数据到缓存中,以后每一次的读取,都是在缓存中访问,直到缓存中的数据读取完毕,再到硬盘中读取。

有的时候,需要立即把数据写入到硬盘,而不是等缓存满了才写出去。 这时候就需要用到flush方法

字节缓冲输出流:BufferedOutputStream

	BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));
	bos.write("hello".getBytes());
	bos.close();

字节缓冲输入流:BufferedInputStream

	BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bos.txt"));

	byte[] bys = new byte[1024];
	int len = 0;
	while ((len = bis.read(bys)) != -1) {
		System.out.print(new String(bys, 0, len));
	}

	bis.close();

缓存字符输入流 BufferedReader

    File f = new File("d:/lol.txt");
    // 创建文件字符流
    // 缓存流必须建立在一个存在的流的基础上
    try (
            FileReader fr = new FileReader(f);
            BufferedReader br = new BufferedReader(fr);
        )
    {
        while (true) {
            // 一次读一行
            String line = br.readLine();
            if (null == line)
                break;
            System.out.println(line);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

缓存字符输出流 PrintWriter

	// 向文件lol2.txt中写入三行语句
    File f = new File("d:/lol2.txt");
      
    try (
            // 创建文件字符流
            FileWriter fw = new FileWriter(f);
            // 缓存流必须建立在一个存在的流的基础上              
            PrintWriter pw = new PrintWriter(fw);              
    ) {
        pw.println("garen kill teemo");
        pw.println("teemo revive after 1 minutes");
        pw.println("teemo try to garen, but killed again");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值