[英]I can't fetch documents from the downloads folder in android
我正在嘗試從下載文件夾中附加文檔。 但是我收到錯誤“java.io.FileNotFoundException:/storage/emulated/0/DownloadReact-native commands.pdf(沒有這樣的文件或目錄)”。這里我展示了我用來獲取路徑的代碼。
if (isDownloadsDocument(uri)) {
Log.d("build_version_one", Build.VERSION.SDK_INT.toString())
Log.d("build_version_two", Build.VERSION_CODES.M.toString())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val id: String
var cursor: Cursor? = null
try {
cursor = context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)
if (cursor != null && cursor.moveToFirst()) {
val fileName = cursor.getString(0)
// val path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName
val path = Environment.getExternalStorageDirectory().toString() +"/Download" + fileName
val ss = Environment.getExternalStoragePublicDirectory("").toString()+"/Download" + fileName
Log.d("orginal_path","one"+path)
Log.d("orginal_path","two"+ss)
if (!TextUtils.isEmpty(path)) {
Log.d("orginal_path","working")
return path
}
}
} finally {
cursor?.close()
}
id = DocumentsContract.getDocumentId(uri)
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:".toRegex(), "")
}
val contentUriPrefixesToTry = arrayOf(
"content://downloads/public_downloads",
"content://downloads/my_downloads"
)
for (contentUriPrefix in contentUriPrefixesToTry) {
return try {
val contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), java.lang.Long.valueOf(id))
Log.d("orginal_content_uri", contentUri.toString())
/* final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));*/
getDataColumn(context, contentUri, null, null)
} catch (e: NumberFormatException) {
//In Android 8 and Android P the id is not a number
uri.path.replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "")
}
}
}
}
}
正如異常所指出的,您的磁盤上沒有這樣的文件/目錄,或者提供的路徑不正確。
乍一看,您似乎錯過了文件名和下載目錄/storage/emulated/0/DownloadReact-native commands.pdf
之間的斜線。 確保文件名和路徑之間有斜線。
val path = Environment.getExternalStorageDirectory().toString() +"/Download/" + fileName
val ss = Environment.getExternalStoragePublicDirectory("").toString()+"/Download/" + fileName
看看它是否有效。 否則,請驗證您是否在相應目錄中歸檔。
getExternalStorageDirectory
在 API 級別 29 java 中已棄用。 使用getExternalFilesDir()
、 getExternalCacheDir()
或getExternalMediaDir()
(上下文方法)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.