這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)Android中怎么保證數(shù)據(jù)同步寫入磁盤,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)新互聯(lián)專注于九原網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供九原營(yíng)銷型網(wǎng)站建設(shè),九原網(wǎng)站制作、九原網(wǎng)頁設(shè)計(jì)、九原網(wǎng)站官網(wǎng)定制、小程序設(shè)計(jì)服務(wù),打造九原網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供九原網(wǎng)站排名全網(wǎng)營(yíng)銷落地服務(wù)。
在一些特定的工作場(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(); }
上述就是小編為大家分享的Android中怎么保證數(shù)據(jù)同步寫入磁盤了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。