看完之后这个答案 https://stackoverflow.com/questions/7849528/fileoutputstream-close-is-really-slow-when-writing-large-file#7849941来自@Peter Lawrey,尤其是这句话:
close()
可以确保文件实际写入磁盘(或不取决于操作系统)
(emphasis is mine.)
我有 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() http://docs.oracle.com/javase/7/docs/api/java/io/FileDescriptor.html#sync()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)