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

拈花ヽ惹草 提交于 2019-12-23 12:57:23

问题


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 ?

回答1:


fileOutputstream.getFD().sync()

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



来源:https://stackoverflow.com/questions/25910173/fileoutputstream-close-is-not-always-writing-bytes-to-file-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!