欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android设备如何保证数据同步写入磁盘的实现

程序员文章站 2022-04-16 15:58:06
在一些特定的工作场景中,我们把数据及时写出磁盘,而不是暂时保存在系统的文件缓存区,防止掉电导致数据丢失 /** * force all system buff...

在一些特定的工作场景中,我们把数据及时写出磁盘,而不是暂时保存在系统的文件缓存区,防止掉电导致数据丢失

/**
 * force all system buffers to synchronize with the underlying
 * device. this method returns after all modified data and
 * attributes of this filedescriptor have been written to the
 * relevant device(s). in particular, if this filedescriptor
 * refers to a physical storage medium, such as a file in a file
 * system, sync will not return until all in-memory modified copies
 * of buffers associated with this filedescriptor have been
 * written to the physical medium.
 *
 * sync is meant to be used by code that requires physical
 * storage (such as a file) to be in a known state for
 * example, a class that provided a simple transaction facility
 * might use sync to ensure that all changes to a file caused
 * by a given transaction were recorded on a storage medium.
 *
 * sync only affects buffers downstream of this filedescriptor. if
 * any in-memory buffering is being done by the application (for
 * example, by a bufferedoutputstream object), those buffers must
 * be flushed into the filedescriptor (for example, by invoking
 * outputstream.flush) before that data will be affected by sync.
 *
 * @exception syncfailedexception
 *    thrown when the buffers cannot be flushed,
 *    or because the system cannot guarantee that all the
 *    buffers have been synchronized with physical media.
 * @since   jdk1.1
 */
public native void sync() throws syncfailedexception;

可能一看到这个场景,很多人会想到数据库的事务,查看android数据库sqlite的源码可以看到,数据库事务只能保证n个操作,要么都执行,要么都不执行。数据库事务在所有操作完成后,会提醒文件系统与磁盘同步,但是不会等到所有系统缓冲区与磁盘同步完成才返回!

  filedescriptor.getfd().sync();会强制所有系统缓冲区与磁盘同步
file file = new file("/sdcard/a.txt");
    try {
      fileoutputstream outputstream = new fileoutputstream(file);
      outputstream.write("kuangxf".getbytes());
      outputstream.flush();
      //强制文件系统刷新
      outputstream.getfd().sync();
    } catch (exception e) {
      e.printstacktrace();
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。