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

所属分类: 软件编程 / java 阅读数: 40
收藏 0 赞 0 分享

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

/**
 * 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();
    }

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

更多精彩内容其他人还在看

Java Set简介_动力节点Java学院整理

Set最大的特性就是不允许在其中存放的元素是重复的。接下来通过本文给大家分享java set常用方法和原理分析,需要的的朋友参考下吧
收藏 0 赞 0 分享

Java Timezone类常见问题_动力节点Java学院整理

这篇文章主要介绍了Java Timezone类常见问题的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

javaWeb项目部署到阿里云服务器步骤详解

本篇文章主要介绍了javaWeb项目部署到阿里云服务器步骤详解,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

详解使用zxing库生成QR-Code二维码

这篇文章主要介绍了详解使用zxing库生成QR-Code二维码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

java实现对服务器的自动巡检邮件通知

这篇文章主要为大家详细介绍了java实现对服务器的自动巡检邮件通知,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

java随机验证码生成实现实例代码

这篇文章主要介绍了java随机验证码生成实现实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

java读取txt文件代码片段

这篇文章主要为大家详细介绍了java读取txt文件的代码片段,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

java连接mysql数据库的方法

这篇文章主要为大家详细介绍了java连接mysql数据库的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

java 算法之快速排序实现代码

这篇文章主要介绍了java 算法之快速排序实现代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用

这篇文章主要介绍了详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多