FileOutputstream.close()并不总是字节写入文件系统? [英] FileOutputstream.close() is not always writing bytes to file system?

查看:852
本文介绍了FileOutputstream.close()并不总是字节写入文件系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看完<一个href=\"http://stackoverflow.com/questions/7849528/fileoutputstream-close-is-really-slow-when-writing-large-file#7849941\">this从@Peter Lawrey回答特别是这一句:


  

的close()可以确保文件实际上被写到磁盘(或不依赖于操作系统


<子>(重点是我的。)

我有3个问题:


  • 这是真的,我们无法保证在调用后的所有字节将可在磁盘的close()? (我猜,因为它从@Peter Lawrey来这是真的)


  • 在一般(即有效上的所有OS),什么是要确保所有字节有效地写入磁盘的最佳方式? (我能想象计数写入流的字节数,和等到 file.length()== BYTECOUNT ...但有一个更好的办法?)


  • 在特定的,在 Android版,是足以称之为 fileOutputStream.close(),以确保所有字节都有效写入文件系统?


下面是一些code(忽略例外,......保持简单)来说明我的文章

 最后的InputStream河道= getInputStreamFromSomewhere();
    最终的FileOutputStream的OutputStream =新的FileOutputStream(someExistingFile);
    INT升;
    最后一个字节[] TMP =新的字节[1024];
    而((1- = instream.read(TMP))!= - 1){
            outstream.write(TMP,0,1);
    }
    instream.close();
    //outputStream.flush(); //因为outputStream.flush()无用的呼叫做什么的FileOutputStream
    outputStream.close();
    //在这点:都字节写入磁盘?


解决方案

  fileOutputstream.getFD()。同步()

应该做你想要什么。请参见 http://docs.oracle。 COM / JavaSE的/ 7 /文档/ API / JAVA / IO / FileDescriptor.html#同步()

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()

这篇关于FileOutputstream.close()并不总是字节写入文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆