Android設(shè)備如何保證數(shù)據(jù)同步寫(xiě)入磁盤(pán)的實(shí)現(xiàn)
在一些特定的工作場(chǎng)景中,我們把數(shù)據(jù)及時(shí)寫(xiě)出磁盤(pán),而不是暫時(shí)保存在系統(tǒng)的文件緩存區(qū),防止掉電導(dǎo)致數(shù)據(jù)丟失
/** * 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;
可能一看到這個(gè)場(chǎng)景,很多人會(huì)想到數(shù)據(jù)庫(kù)的事務(wù),查看Android數(shù)據(jù)庫(kù)sqlite的源碼可以看到,數(shù)據(jù)庫(kù)事務(wù)只能保證n個(gè)操作,要么都執(zhí)行,要么都不執(zhí)行。數(shù)據(jù)庫(kù)事務(wù)在所有操作完成后,會(huì)提醒文件系統(tǒng)與磁盤(pán)同步,但是不會(huì)等到所有系統(tǒng)緩沖區(qū)與磁盤(pán)同步完成才返回!
FileDescriptor.getFd().sync();會(huì)強(qiáng)制所有系統(tǒng)緩沖區(qū)與磁盤(pán)同步 File file = new File("/sdcard/a.txt"); try { FileOutputStream outputStream = new FileOutputStream(file); outputStream.write("kuangxf".getBytes()); outputStream.flush(); //強(qiáng)制文件系統(tǒng)刷新 outputStream.getFD().sync(); } catch (Exception e) { e.printStackTrace(); }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
HDFS?Balancer負(fù)載均衡器及語(yǔ)法詳解
這篇文章主要為大家介紹了HDFS?Balancer負(fù)載均衡器及語(yǔ)法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03Java正則驗(yàn)證正整數(shù)的方法分析【測(cè)試可用】
這篇文章主要介紹了Java正則驗(yàn)證正整數(shù)的方法,結(jié)合實(shí)例形式對(duì)比分析了java針對(duì)正整數(shù)的驗(yàn)證方法及相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-08-08定時(shí)任務(wù)注解@Scheduled不生效問(wèn)題及解決
這篇文章主要介紹了定時(shí)任務(wù)注解@Scheduled不生效問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06詳解JSON與?Java對(duì)象之間的轉(zhuǎn)化
在現(xiàn)在的日常開(kāi)發(fā)中,不管前端還是后端,JSON?格式的數(shù)據(jù)是用得比較多的,甚至可以說(shuō)無(wú)處不在。所以本文主要來(lái)講講JSON?格式的數(shù)據(jù)與?Java?對(duì)象之間的轉(zhuǎn)化吧2023-03-03深入Parquet文件格式設(shè)計(jì)原理及實(shí)現(xiàn)細(xì)節(jié)
這篇文章主要介紹了深入Parquet文件格式設(shè)計(jì)原理及實(shí)現(xiàn)細(xì)節(jié),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08