您好,登錄后才能下訂單哦!
在一些特定的工作場景中,我們把數(shù)據(jù)及時寫出磁盤,而不是暫時保存在系統(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;
可能一看到這個場景,很多人會想到數(shù)據(jù)庫的事務(wù),查看Android數(shù)據(jù)庫sqlite的源碼可以看到,數(shù)據(jù)庫事務(wù)只能保證n個操作,要么都執(zhí)行,要么都不執(zhí)行。數(shù)據(jù)庫事務(wù)在所有操作完成后,會提醒文件系統(tǒng)與磁盤同步,但是不會等到所有系統(tǒng)緩沖區(qū)與磁盤同步完成才返回!
FileDescriptor.getFd().sync();會強(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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。