gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:47:51 29 4
gpt4 key购买 nike

看完this answer来自@Peter Lawrey 特别是这句话:

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()

应该做你想做的。参见 http://docs.oracle.com/javase/7/docs/api/java/io/FileDescriptor.html#sync()

关于java - FileOutputstream.close() 并不总是将字节写入文件系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25910173/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com