从@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