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();
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗搜寻
2 如何训练狗狗装死
3 狗狗训练书
6 怎么训练狗狗拜年
8 狗狗训练游戏
10 狗狗嗅觉训练
11 怎么训练狗狗在笼子里不叫
12 怎么训练狗狗站立走路
13 怎么训练狗狗在马桶上
14 狗狗尿尿怎么训练
15 训练狗狗用品
16 泰迪狗狗的训练方法大小便
17 训练狗狗可以打吗
18 王曼丽的狗狗训练