使用 api 非常簡單,可直接參閱 官方文檔,這里僅對(duì)其路徑常量做一個(gè)簡單解釋
android
MainBundlePath: undefined
DocumentDirectoryPath: "/data/user/0/com.project/files"
LibraryDirectoryPath: undefined
CachesDirectoryPath: "/data/user/0/com.project/cache"
TemporaryDirectoryPath: "/data/user/0/com.project/cache"
ExternalDirectoryPath: "/storage/emulated/0/Android/data/com.project/files"
ExternalCachesDirectoryPath: "/storage/emulated/0/Android/data/com.project/cache"
ExternalStorageDirectoryPath: "/storage/emulated/0"
PicturesDirectoryPath: "/storage/emulated/0/Pictures"
FileProtectionKeys: undefined
iOS
MainBundlePath: "/data/Containers/Bundle/Application/E57.../project.app"
DocumentDirectoryPath: "/data/Containers/Data/Application/F18.../Documents"
LibraryDirectoryPath: "/data/Containers/Data/Application/F18.../Library"
CachesDirectoryPath: "/data/Containers/Data/Application/F18.../Library/Caches"
TemporaryDirectoryPath: "/data/Containers/Data/Application/F18.../tmp"
ExternalDirectoryPath: null
ExternalCachesDirectoryPath: undefined
ExternalStorageDirectoryPath: null
PicturesDirectoryPath: undefined
FileProtectionKeys: undefined
MainBundlePath
打包 app 的絕對(duì)路徑,相當(dāng)于你可以直接讀取 app 內(nèi)部的一些資源文件,僅在 iOS 下可用,使用的時(shí)候要注意拼接路徑; android 沒這個(gè)東西,做雙平臺(tái)的話,應(yīng)避免使用這個(gè),也沒必要,把資源直接打包,也會(huì)增加安裝包體積
DocumentDirectoryPath
存放 app 使用過程中產(chǎn)生的用戶私人文件,可持久化保存,iTunes iCloud 備份/恢復(fù)包含此目錄,想必 android 應(yīng)該是同理的
LibraryDirectoryPath
存儲(chǔ)配合應(yīng)用程序的其他非個(gè)人文件的數(shù)據(jù),比如一些應(yīng)用程序的配置文件啥的,android 沒有這個(gè)目錄,也應(yīng)盡量避免使用,當(dāng)需要存儲(chǔ)此類數(shù)據(jù),建議放到 CachesDirectoryPath
CachesDirectoryPath
應(yīng)用程序數(shù)據(jù)緩存目錄,可持久化保存,但可能面臨被清除的風(fēng)險(xiǎn)(比如一些清理垃圾文件的操作),所以應(yīng)用程序如果使用該目錄應(yīng)該做兜底處理
TemporaryDirectoryPath
臨時(shí)文件目錄,這個(gè)純粹是臨時(shí)的,重啟手機(jī),或者文件過多,系統(tǒng)層面就直接清除這個(gè)目錄,都無需用戶去特意觸發(fā),用來存放用一下子就仍的文件。 Android 沒這個(gè)目錄,react-native-fs 默認(rèn)返回了 CachesDirectoryPath 的路徑
ExternalDirectoryPath
ExternalStorageDirectoryPath
sd卡目錄,僅在 Android 上生效,對(duì)應(yīng)著 DocumentDirectoryPath、CachesDirectoryPath,無需申請(qǐng)權(quán)限,屬于應(yīng)用專屬目錄
ExternalStorageDirectoryPath
PicturesDirectoryPath
看路徑應(yīng)該是 android 共享的 sd 卡目錄,需要申請(qǐng)權(quán)限才能使用,由于是 android only,且需要權(quán)限,也建議盡量不使用
FileProtectionKeys
沒看到項(xiàng)目中提到,暫且不理會(huì)
總結(jié)
寫永久保存的個(gè)人文件,用
DocumentDirectoryPath是最好的,雙平臺(tái)兼容。寫緩存文件用
CachesDirectoryPath最好,也是雙平臺(tái)兼容。寫臨時(shí)文件,iOS 可直接用
TemporaryDirectoryPath, android 建議使用CachesDirectoryPath,用完之后手動(dòng)刪除,可將二者封裝為一個(gè)兼容的函數(shù)Android SD 卡,除非是做文件管理相關(guān)的應(yīng)用,不建議使用相關(guān)路徑,畢竟現(xiàn)在的手機(jī)存儲(chǔ)空間都比較大,甚至不少手機(jī)都取消了 sd 卡