java fileoutputstream close_java – FileOutputstream.close()并不总是将字节写入文件系统?...

从@Peter Lawrey阅读this answer之后,尤其是这句话:

close() can ensure the file is actually written to disk (or not depending on the OS)

(重点是我的.)

我有3个问题:

>在调用close()之后,没有保证所有字节都可用于磁盘上,这是真的吗? (我想这是真的,因为它来自@Peter Lawrey)

>一般情况下(即在所有操作系统上都有效),确保所有字节都有效写入磁盘的最佳方法是什么? (我可以想象计算写入流的字节数,并等到file.length()== byteCount …但是有更好的方法吗?)

>特别是在Android上,调用fileOutputStream.close()是否足以确保所有字节都有效地写入文件系统?

这里有一些代码(忽略异常,…以保持简单)来说明我的帖子

final InputStream instream = getInputStreamFromSomewhere();

final FileOutputStream outputstream = new FileOutputStream(someExistingFile);

int l;

final byte[] tmp = new byte[1024];

while ((l = instream.read(tmp)) != -1) {

outstream.write(tmp, 0, l);

}

instream.close();

//outputStream.flush(); //useless call since outputStream.flush() do nothing on FileOutputStream

outputStream.close();

//at this point : are all bytes written to disk ?

解决方法:

fileOutputstream.getFD().sync()

标签:java,android,filesystems,java-io

来源: https://codeday.me/bug/20190609/1207427.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值