关于BufferedOutputStream的flush方法

本文探讨了在使用BufferedOutputStream时遇到的写入不完整问题,通过研究和示例,阐述了flush()方法的重要性和工作原理。该方法在println、写入换行字符或字节后自动调用,确保数据正确输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前发现用BufferedOutputStream写如流,写入不完整,之后查了资料,对这个方法有了新的认识。
java flush()函数的作用
写个小例子记录一下

BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("/Users/apple/Documents/x1.txt"));
        //x.txt文件小于6k
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/apple/Documents/x.txt")));
        String len;
        while ((len = in.readLine()) != null) {
            out.write(len.getBytes());
        }
        //不写这句话x1.txt文件什么也没有
        out.flush();

后来查阅资料发现PrintStream这个类,这个类主要是起装饰作用,方便输出各种格式
这里写图片描述
从API描述中
只要用户调用println方法之一或写入换行字符或字节(‘\n’)后,会自动调用flush方法。

 BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/apple/Documents/x.txt")));
        PrintStream out = new PrintStream("/Users/apple/Documents/x1.txt");
        String len;
        while ((len = in.readLine()) != null) {
            out.write(len.getBytes());
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值