FileOutputstream.close()是否不总是将字节写入文件系统?

ben*_*n75 4 java filesystems android java-io

在阅读完@Peter Lawrey的答案后,尤其是这句话:

close()可以确保将文件实际写入磁盘(或不取决于操作系统

(重点是我的。)

我有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 ?
Run Code Online (Sandbox Code Playgroud)