After reading this answer from @Peter Lawrey and especially this sentence :
close()
can ensure the file is actually written to disk (or not depending on the OS)
(emphasis is mine.)
I have 3 questions :
Is it true that there is no guaranty that all the bytes will be available on disk after calling close()
? (I guess it's true since it came from @Peter Lawrey)
In general (i.e. valid on all OS), what is the best way to be sure that all bytes are effectively written to disk ? (I can imagine counting the bytes written to the stream, and waiting until file.length() == byteCount
... but is there a better approach ?)
In particular, on Android, is it enough to call fileOutputStream.close()
to be sure that all bytes are effectively written to the file system ?
Here is some code (ignoring exceptions, ... to keep it simple) to illustrate my post
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()
should do what you want. See http://docs.oracle.com/javase/7/docs/api/java/io/FileDescriptor.html#sync()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With