Android設(shè)備如何保證數(shù)據(jù)同步寫入磁盤的實(shí)現(xiàn)
在一些特定的工作場(chǎng)景中,我們把數(shù)據(jù)及時(shí)寫出磁盤,而不是暫時(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ù)庫的事務(wù),查看Android數(shù)據(jù)庫sqlite的源碼可以看到,數(shù)據(jù)庫事務(wù)只能保證n個(gè)操作,要么都執(zhí)行,要么都不執(zhí)行。數(shù)據(jù)庫事務(wù)在所有操作完成后,會(huì)提醒文件系統(tǒng)與磁盤同步,但是不會(huì)等到所有系統(tǒng)緩沖區(qū)與磁盤同步完成才返回!
FileDescriptor.getFd().sync();會(huì)強(qiáng)制所有系統(tǒng)緩沖區(qū)與磁盤同步
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();
}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot實(shí)現(xiàn)接口文檔自動(dòng)生成的方法示例
在開發(fā)Web應(yīng)用程序時(shí),接口文檔是非常重要的一環(huán),本文主要介紹了SpringBoot實(shí)現(xiàn)接口文檔自動(dòng)生成的方法示例,具有一定的參考價(jià)值,感興趣的可以了解一下2023-10-10
基于java ssm springboot+mybatis酒莊內(nèi)部管理系統(tǒng)設(shè)計(jì)和實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了java ssm springboot+mybatis實(shí)現(xiàn)酒店管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
SpringBoot如何配置數(shù)據(jù)庫主從shardingsphere
這篇文章主要介紹了SpringBoot如何配置數(shù)據(jù)庫主從shardingsphere問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
Java的Lambda表達(dá)式和Stream流的作用以及示例
這篇文章主要介紹了Java的Lambda表達(dá)式和Stream流簡(jiǎn)單示例,Lambda允許把函數(shù)作為一個(gè)方法的參數(shù),使用Lambda表達(dá)式可以寫出更簡(jiǎn)潔、更靈活的代碼,而其作為一種更緊湊的代碼風(fēng)格,使Java的語言表達(dá)能力得到了提升,需要的朋友可以參考下2023-05-05

