Android设备如何保证数据同步写入磁盘的实现
2019-12-25 12:03
2875 查看
在一些特定的工作场景中,我们把数据及时写出磁盘,而不是暂时保存在系统的文件缓存区,防止掉电导致数据丢失
/** * 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开发] 在Android开发时,如何实现和服务器的数据同步?
- Android开发如何实现和服务器的数据同步
- 设备驱动中环形缓冲区数据存储和读写同步的实现[转自:http://hi.baidu.com/whandsome/blog/item/3834e32a9994692cd52af1f9.html]
- 如何在SQL Server 2005中实现数据同步
- android中bluedroid如何读取pcm数据,并将其写入文件中?
- 如何保证向两个服务器插入数据能同步
- 深入学习:如何实现不同Android设备之间相同应用程序的网络服务发现功能
- 手把手教你实现Android中智能设备数据表格绘制
- 【Android开发技巧】在Activity页面中如何实现Fragment数据的缓加载
- 如何在两个SQLSERVER之间实现数据同步
- android开发 如何通过web服务器访问MYSQL数据库并且使其数据同步到android SQLite数据库?
- Nunchuck.js - 轻松实现多个设备的数据同步
- Android中如何获取在非Root设备中获取应用隐私数据
- Android逆向之旅---Android中如何获取在非Root设备中获取应用隐私数据
- sync 数据同步写入磁盘
- android 设备写入文件,立即断电重启后,文件丢失,数据没有保存问题
- 设备驱动中环形缓冲区数据存储和读写同步的实现
- 同步所有已挂载的文件系统。所有缓存中的数据将被立刻写入磁盘
- Android中后台定时任务实现,即时数据同步问题思考!
- win2003如何为共享文件所在的磁盘进行配额保障数据正常写入