什么是最简单的方法从android.net.Uri对象持有一个文件:类型转换为java.io.File对象在Android?

我尝试了下面的方法,但不管用:

File file = new File(Environment.getExternalStorageDirectory(), "read.me");
Uri uri = Uri.fromFile(file);
File auxFile = new File(uri.toString());
assertEquals(file.getAbsolutePath(), auxFile.getAbsolutePath());

当前回答

科特林 2022

suspend fun Context.createFileFromAsset(assetName: String, fileName: String): File? {
    return withContext(Dispatchers.IO) {
        runCatching {
            val stream = assets.open(assetName)
            val file = File(cacheDir.absolutePath, fileName)
            org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, file)
            file
        }.onFailure { Timber.e(it) }.getOrNull()
    }
}

处理完文件后,请确保对其调用.delete()。向@Mohsent致敬

其他回答

public String getRealPathFromURI(Uri uri) {

    String result;
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    if (cursor == null) {
        result = uri.getPath();
        cursor.close();
        return result;
    }
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    result = cursor.getString(idx);
    cursor.close();
    return result;
}

然后使用从URI中获取文件:

        File finalFile = newFile(getRealPathFromURI(uri));

——希望能帮到你----

使用Kotlin甚至更容易:

val file = File(uri.path)

或者如果你在Android上使用Kotlin扩展:

val file = uri.toFile()

更新: 对于图像,它返回“Uri缺少'file' scheme: content://”

谢谢你的评论

你可以使用这个函数从uri中获取文件在新的android和旧的

fun getFileFromUri(context: Context, uri: Uri?): File? {
    uri ?: return null
    uri.path ?: return null

    var newUriString = uri.toString()
    newUriString = newUriString.replace(
        "content://com.android.providers.downloads.documents/",
        "content://com.android.providers.media.documents/"
    )
    newUriString = newUriString.replace(
        "/msf%3A", "/image%3A"
    )
    val newUri = Uri.parse(newUriString)

    var realPath = String()
    val databaseUri: Uri
    val selection: String?
    val selectionArgs: Array<String>?
    if (newUri.path?.contains("/document/image:") == true) {
        databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        selection = "_id=?"
        selectionArgs = arrayOf(DocumentsContract.getDocumentId(newUri).split(":")[1])
    } else {
        databaseUri = newUri
        selection = null
        selectionArgs = null
    }
    try {
        val column = "_data"
        val projection = arrayOf(column)
        val cursor = context.contentResolver.query(
            databaseUri,
            projection,
            selection,
            selectionArgs,
            null
        )
        cursor?.let {
            if (it.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow(column)
                realPath = cursor.getString(columnIndex)
            }
            cursor.close()
        }
    } catch (e: Exception) {
        Log.i("GetFileUri Exception:", e.message ?: "")
    }
    val path = realPath.ifEmpty {
        when {
            newUri.path?.contains("/document/raw:") == true -> newUri.path?.replace(
                "/document/raw:",
                ""
            )
            newUri.path?.contains("/document/primary:") == true -> newUri.path?.replace(
                "/document/primary:",
                "/storage/emulated/0/"
            )
            else -> return null
        }
    }
    return if (path.isNullOrEmpty()) null else File(path)
}

科特林 2022

suspend fun Context.createFileFromAsset(assetName: String, fileName: String): File? {
    return withContext(Dispatchers.IO) {
        runCatching {
            val stream = assets.open(assetName)
            val file = File(cacheDir.absolutePath, fileName)
            org.apache.commons.io.FileUtils.copyInputStreamToFile(stream, file)
            file
        }.onFailure { Timber.e(it) }.getOrNull()
    }
}

处理完文件后,请确保对其调用.delete()。向@Mohsent致敬

@CommonsWare解释得很好。我们真的应该采用他提出的解决方案。

顺便说一下,当查询ContentResolver时,我们唯一可以依赖的信息是文件的名称和大小,如下所述: 检索文件信息| Android开发人员

正如您所看到的,这里有一个接口OpenableColumns,它只包含两个字段:DISPLAY_NAME和SIZE。

在我的例子中,我需要检索关于JPEG图像的EXIF信息,并在发送到服务器之前根据需要旋转它。为此,我使用ContentResolver和openInputStream()将文件内容复制到临时文件中。