写入文件(ByteArray)并返回Uri时出现空对象引用错误

Null object reference error when writing the file (ByteArray) and returning Uri

我写这个函数是为了保存文件和 return 文件 Uri。但是 rootfile 变量总是空的,所以它在最后抛出一个 NPE。

fun writeFile(context: Context, fileName: String, body: ByteArray): Uri? {
        val fname = "${Environment.getExternalStorageDirectory().absolutePath}/ardata"
        val root = File(fname)
        if (!root.exists()) {
            root.mkdirs()
        }

        try {
            val file = File(root, fileName)
            file.writeBytes(body)
            file.setExecutable(true)
            return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

return 抛出 NPE 消息:

Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

这是我的变量在函数结束时的样子

如何保存文件 (ByteArray) 和 return URI?

您可以使用

 val path = Environment.getExternalStorageDirectory().toString();
                OutputStream fOut;
                File file = File(path, System.currentTimeMillis().toString() + ".mp4");
                    fOut = FileOutputStream(file);
        fos.write(byteArray);
        fos.close();
Uri uri = Uri.fromFile(file);
return uri;

我将 return 更改为 Uri.parse 并开始工作

    val fname = "${Environment.getExternalStorageDirectory().absolutePath}/ardata"
    val root = File(fname)
    if (!root.exists()) {
        root.mkdirs()
    }

    try {
        val file = File(root, fileName)
        file.writeBytes(body)
        file.setExecutable(true)
        val obj = file.path
        return Uri.parse(obj)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null