![](/img/trans.png)
[英]Difference between Context.openFileInput() and using the Java.IO classes
[英]Synchronization between Context.openFileInput and Context.openFileOutput
我有一個每天運行的Android Service
,它可以進行一些數據同步。 每天一次下載文件並通過context.openFileOutput
其緩存到磁盤:
String fileName = Uri.parse(url).getLastPathSegment();
try (FileOutputStream outputStream =
context.openFileOutput(fileName, Context.MODE_PRIVATE)) {
outputStream.write(bytes);
// ...
} catch (IOException e) {
// logging ...
}
這發生在后台線程上。 我還有一個包含WebView
的UI。 如果可以通過context.openFileInput
使用這些緩存資源, WebView
將使用這些資源:
@Override
public WebResourceResponse shouldInterceptRequest(
WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (shouldUseCache(url)) {
try {
return new WebResourceResponse(
"video/webm",
Charsets.UTF_8.name(),
context.openFileInput(obtainFileName(url)));
} catch (IOException e) {
// If a cached resource fails to load, just let the WebView load it the normal way.
// logging ...
}
}
return super.shouldInterceptRequest(view, request);
}
這發生在獨立於服務的另一個后台線程上。
我可以依賴Context
實現並確保文件讀寫是安全的,還是我必須自己處理同步? 例如,如果Service
當前正在將數據寫入文件並且WebView
正在嘗試訪問它,那么我是否會遇到問題? 如果是這樣,我該如何實現同步?
如果服務當前正在將數據寫入文件並且WebView正在嘗試訪問它,那么我是否會遇到問題?
在這種情況下,您可以通過在文件名中附加內容並在下載完成后更改其名稱來將數據寫入文件。 例如
context.openFileOutput(fileName + ".downloading", Context.MODE_PRIVATE))
然后一旦下載完成,將文件重命名為原始fileName
。 我確定您在shouldUseCache(url)
檢查文件是否存在,以便它能夠繼續正常工作。 這將避免在您嘗試讀取文件時仍在下載文件的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.