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

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

 

Android设备如何保证数据同步写入磁盘_第1张图片

 

 

更多相关文章

  1. android SQLite数据库2
  2. Android 创建SQLite数据库(一)
  3. Android 中数据库查询方法 query() 中的 selectionArgs 的用法
  4. android中的sqlit3数据库进行手机应用软件开发(自写的一个财务管
  5. Android系统配置数据库注释(settings.db)
  6. Android 中数据库查询方法 query() 中的 select
  7. android SQLite数据库基本操作示例
  8. android之sqlite数据库初级
  9. Android 原生SQLite数据库操作实战

随机推荐

  1. 怎么给Android(安卓)控件添加边框(样式)?
  2. Android命令行手动编译打包详解
  3. Android面试题集锦 (陆续更新)
  4. android查询软件(身份证号,号码归属等)源代
  5. android 控件放大缩小效果实现
  6. 其他小知识点
  7. Android 透明度数值
  8. Android上传文件到Web服务器,PHP接收文件(
  9. Android:实现类似RadioButton自动换行及
  10. Android反射出一个类中的其他类对象并调