Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?
like image 310
ben75 Avatar asked Mar 18 '23 10:03

ben75


1 Answers

fileOutputstream.getFD().sync()

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

like image 173
Thomas Stets Avatar answered Apr 07 '23 17:04

Thomas Stets