Android设备如何保证数据同步写入磁盘的实现
在一些特定的工作场景中,我们把数据及时写出磁盘,而不是暂时保存在系统的文件缓存区,防止掉电导致数据丢失
/** *Forceallsystembufferstosynchronizewiththeunderlying *device.Thismethodreturnsafterallmodifieddataand *attributesofthisFileDescriptorhavebeenwrittentothe *relevantdevice(s).Inparticular,ifthisFileDescriptor *referstoaphysicalstoragemedium,suchasafileinafile *system,syncwillnotreturnuntilallin-memorymodifiedcopies *ofbuffersassociatedwiththisFileDescriptorhavebeen *writtentothephysicalmedium. * *syncismeanttobeusedbycodethatrequiresphysical *storage(suchasafile)tobeinaknownstateFor *example,aclassthatprovidedasimpletransactionfacility *mightusesynctoensurethatallchangestoafilecaused *byagiventransactionwererecordedonastoragemedium. * *synconlyaffectsbuffersdownstreamofthisFileDescriptor.If *anyin-memorybufferingisbeingdonebytheapplication(for *example,byaBufferedOutputStreamobject),thosebuffersmust *beflushedintotheFileDescriptor(forexample,byinvoking *OutputStream.flush)beforethatdatawillbeaffectedbysync. * *@exceptionSyncFailedException *Thrownwhenthebufferscannotbeflushed, *orbecausethesystemcannotguaranteethatallthe *buffershavebeensynchronizedwithphysicalmedia. *@sinceJDK1.1 */ publicnativevoidsync()throwsSyncFailedException;
可能一看到这个场景,很多人会想到数据库的事务,查看Android数据库sqlite的源码可以看到,数据库事务只能保证n个操作,要么都执行,要么都不执行。数据库事务在所有操作完成后,会提醒文件系统与磁盘同步,但是不会等到所有系统缓冲区与磁盘同步完成才返回!
FileDescriptor.getFd().sync();会强制所有系统缓冲区与磁盘同步 Filefile=newFile("/sdcard/a.txt"); try{ FileOutputStreamoutputStream=newFileOutputStream(file); outputStream.write("kuangxf".getBytes()); outputStream.flush(); //强制文件系统刷新 outputStream.getFD().sync(); }catch(Exceptione){ e.printStackTrace(); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。