大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这期内容当中小编将会给大家带来有关Android中怎么保证数据同步写入磁盘,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
创新互联专注于九原网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供九原营销型网站建设,九原网站制作、九原网页设计、九原网站官网定制、小程序设计服务,打造九原网络公司原创品牌,更为您提供九原网站排名全网营销落地服务。
在一些特定的工作场景中,我们把数据及时写出磁盘,而不是暂时保存在系统的文件缓存区,防止掉电导致数据丢失
/** * 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中怎么保证数据同步写入磁盘了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。