安卓10无法通过URI编辑文件。
创始人
2024-09-01 16:00:26
0

在Android 10中,由于隐私和安全方面的改进,应用无法直接通过URI来编辑文件。相反,您需要使用ContentResolver和DocumentFile来进行文件编辑操作。

以下是通过ContentResolver和DocumentFile在Android 10中编辑文件的示例代码:

import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import androidx.annotation.RequiresApi;
import androidx.documentfile.provider.DocumentFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileEditor {
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static void editFile(Context context, Uri uri, String content) {
        ContentResolver resolver = context.getContentResolver();

        // 根据URI获取文件信息
        DocumentFile documentFile = DocumentFile.fromSingleUri(context, uri);

        // 获取文件的MIME类型
        String mimeType = resolver.getType(uri);

        try {
            // 打开文件的输出流
            OutputStream outputStream = resolver.openOutputStream(uri);

            // 写入内容到文件
            outputStream.write(content.getBytes());

            // 关闭输出流
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,我们首先通过ContentResolver获取文件的MIME类型,然后使用DocumentFile来打开文件的输出流,并将内容写入文件。请注意,这个示例代码在Android 10及以上版本上有效。

使用示例:

Uri fileUri = Uri.parse("content://com.example.app/file/document/1234");
String content = "Hello, Android 10!";
FileEditor.editFile(context, fileUri, content);

在上述示例中,我们传递文件的URI和要写入的内容给editFile()方法,它将使用ContentResolver和DocumentFile来编辑文件。

请注意,上述代码中的URI是示例URI,您需要根据您的实际情况替换为您要编辑的文件的URI。此外,您还需要在AndroidManifest.xml文件中添加相关的权限和文件访问声明。

相关内容

热门资讯

透视游戏!wepoker私人局... 透视游戏!wepoker私人局透视方法,wepoker透视脚本免费,窍要教程(有挂分析)-哔哩哔哩1...
透视黑科技!德州透视插件,hh... 透视黑科技!德州透视插件,hhpoker有没有辅助,总结教程(有挂教学)-哔哩哔哩1、下载好hhpo...
透视苹果版!hhpoker怎么... 透视苹果版!hhpoker怎么破解,hhpoker德州牛仔视频,积累教程(有挂方针)-哔哩哔哩1、任...
透视科技!wpk透视是真的假的... 透视科技!wpk透视是真的假的,德州局怎么透视,法门教程(有挂透视)-哔哩哔哩1、让任何用户在无需w...
透视辅助!wpk插件辅助,约局... 透视辅助!wpk插件辅助,约局吧德州真的存在透视吗,总结教程(有挂实锤)-哔哩哔哩1)约局吧德州真的...
透视能赢!wepoker免费脚... 透视能赢!wepoker免费脚本弱密码,hhpoker底牌透视脚本,策略教程(有挂功能)-哔哩哔哩1...
透视好友房!poker辅助器免... 透视好友房!poker辅助器免费安装,hhpoker辅助软件下载,绝活教程(有挂工具)-哔哩哔哩1、...
透视脚本!佛手大菠萝13道挂哪... 透视脚本!佛手大菠萝13道挂哪里,德州辅助工具到底怎么样,要领教程(有挂方法)-哔哩哔哩德州辅助工具...
透视中牌率!wepoker辅助... 透视中牌率!wepoker辅助软件视频,红龙poker辅助指令,教程书教程(确实有挂)-哔哩哔哩该软...
透视科技!wepoker辅助工... 透视科技!wepoker辅助工具,智星德州可以透视吗,手筋教程(新版有挂)-哔哩哔哩1、下载好智星德...