使用MediaStore我創建了名為的隨機測驗檔案po.txt:
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "po"); //file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain"); //file extension, will automatically add to file
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS ); //end "/" is not mandatory
Uri uri = getContext().getContentResolver().insert(MediaStore.Files.getContentUri("external"), values); //important!
OutputStream outputStream = getContext().getContentResolver().openOutputStream(uri);
outputStream.write("This is menu category data.".getBytes());
outputStream.close();
File f = new File(uri.getPath());
if(f.exists()) {
Log.e("i","never enter this code :(");
} else {
Log.e("i","always enter this code :(");
}
檔案已創建,我可以毫無問題地打開它們:

但是,為了檢查檔案是否真的被創建,根據if陳述句,即使檔案被實際創建,檔案也不存在。
這是由于這些檔案在創建時無法訪問,還是由于檔案不可讀的正確問題?
uj5u.com熱心網友回復:
ContentProvider 的主要功能之一是封裝資料,因此您不必處理低級別的東西,例如檔案。
我不確定您為什么要測驗您創建的行是否存在,因為只要插入呼叫成功,您就知道它確實存在。該Uri.getPath函式不回傳檔案路徑,而是回傳解碼后的 Uri 路徑,正如您從螢屏截圖中看到的那樣,類似于"content://media/external/file/{some number}".
如果您想打開您創建的行的內容(回傳的 Uri),您可以使用 Intent。請參閱相關的開發人員檔案:內容提供者和意圖過濾器
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446351.html
上一篇:用陣列C語言逐行存盤元素
