FileOutputstream.close() is not always writing bytes to file system?
Asked Answered
C

1

5

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 ?
Crisp answered 18/9, 2014 at 10:27 Comment(3)
As Sagar Pilkwhal suggested (why did he remove his answer?) 1, 2, 3 The answer is: Use flush(); before close();Gyroplane
As far as I know : flush() do noting in a FileOutputStreamCrisp
i have edited my answer, added some more documentation linkHooper
P
7
fileOutputstream.getFD().sync()

should do what you want. See http://docs.oracle.com/javase/7/docs/api/java/io/FileDescriptor.html#sync()

Poyang answered 18/9, 2014 at 10:47 Comment(2)
Agreed. "You sync, you win".Eckblad
2022 this does not work anymoreStatue

© 2022 - 2024 — McMap. All rights reserved.