BufferedOutputStream研究

本文讲解了在文件操作中如何正确地使用write方法避免输出null值,并介绍了flush与close方法的内部实现,帮助开发者理解并避免常见错误。

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

在写文件的时候,调用write方法,有时候我们会像这样直接调用write方法.

bos.write(buffer);

同样我们看看底层:

    public void write(byte b[]) throws IOException {
        write(b, 0, b.length);
    }

如果我们的缓冲区设置为了8192,但是实际的文件比如只有'123'3个字符.

那么我们最后写出的文件就会变成这样:


因为我们读的是b.length,所以最后写文件的时候,虽然后面没有东西输入,但是文件还是会把null null null输出出来.

因此以后我们的工作要养成良好习惯,文件输出的代码应该这么写:

		byte[] buffer=new byte[8192];
		
		while((c = bis.read(buffer))!=-1){
			bos.write(buffer,0,c);
		}
		bis.close();
		bos.close();

这个c就代表你读到数组里面的长度是多少,不会多读,就不会出现null的情况了。

关于flush

很多的代码示例里面会加上

out.flush();

但其实我们看看源码:

public synchronized void write(byte b[], int off, int len) throws IOException {
        if (len >= buf.length) {
            /* If the request length exceeds the size of the output buffer,
               flush the output buffer and then write the data directly.
               In this way buffered streams will cascade harmlessly. */
            flushBuffer();
            out.write(b, off, len);
            return;
        }
        if (len > buf.length - count) {
            flushBuffer();
        }
        System.arraycopy(b, off, buf, count, len);
        count += len;
    }

当你使用

write(byte b[], int off, int len)

这个方法的时候,源码已经帮你判断了,不需要自己flush

再看close()方法:

    public void close() throws IOException {
        try {
          flush();
        } catch (IOException ignored) {
        }
        out.close();
    }

最后close的时候,源码内部也进行了flush().


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值