Android: 在API 29中从现有的URI中覆盖文件
创始人
2024-10-06 01:29:53
0

在Android API 29中,您可以使用ContentResolverDocumentFile类来覆盖现有的文件。以下是一个代码示例:

// 获取要覆盖的文件的URI
Uri fileUri = ...;

// 获取文件的DocumentFile对象
DocumentFile documentFile = DocumentFile.fromSingleUri(context, fileUri);

// 获取文件的父目录的DocumentFile对象
DocumentFile parentDocumentFile = documentFile.getParentFile();

// 创建要覆盖的文件的新DocumentFile对象
String newFileName = "new_file_name.txt";
DocumentFile newDocumentFile = parentDocumentFile.createFile(null, newFileName);

// 打开新文件的输出流
OutputStream outputStream = context.getContentResolver().openOutputStream(newDocumentFile.getUri());

// 将新文件的内容写入输出流,这里假设您有一个输入流来读取文件的内容
InputStream inputStream = ...;
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, bytesRead);
}

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

// 删除原始文件
documentFile.delete();

上述代码中,我们首先使用DocumentFile.fromSingleUri()方法获取要覆盖的文件的DocumentFile对象。然后,我们使用getParentFile()方法获取文件的父目录的DocumentFile对象。

接下来,我们使用createFile()方法在父目录中创建一个新的文件,并传递null作为MIME类型来覆盖现有文件。

然后,我们打开新文件的输出流,并使用输入流从原始文件中读取内容,并将其写入输出流中。

最后,我们关闭输入输出流,并使用delete()方法删除原始文件。

请注意,您需要根据自己的需求修改代码中的部分,例如替换fileUrinewFileName变量。

相关内容

热门资讯

透视普及!德扑之心免费透视(透... 透视普及!德扑之心免费透视(透视)哈糖大菠萝挂,教程秘籍(有挂教程)-哔哩哔哩1、下载好德扑之心免费...
透视透视!hhpoker辅助软... 透视透视!hhpoker辅助软件下载(透视)hhpoker真的有透视吗,教程方案(了解有挂)-哔哩哔...
透视有挂!hhpoker德州透... 透视有挂!hhpoker德州透视(透视)hhpoker透视工具,教程方针(有挂秘笈)-哔哩哔哩在进入...
透视教你!hhpoker俱乐部... 透视教你!hhpoker俱乐部是干嘛的(透视)德普辅助软件,教程阶段(真实有挂)-哔哩哔哩1、点击下...
透视详情!德州hhpoker是... 透视详情!德州hhpoker是真的吗(透视)aa poker辅助包,教程操作(有挂教学)-哔哩哔哩1...
透视揭露!newpoker脚本... 透视揭露!newpoker脚本(透视)聚星ai辅助工具激活码,教程技法(有挂教程)-哔哩哔哩1)聚星...
透视详情!菠萝德普辅助器免费版... 透视详情!菠萝德普辅助器免费版在哪里(透视)wepoker私人局透视插件,教程教材(有挂教学)-哔哩...
透视开挂!we-poker有人... 透视开挂!we-poker有人玩吗(透视)pokemmo脚本,教程练习(有挂细节)-哔哩哔哩1、we...
透视揭幕!wpk系统是否存在透... 透视揭幕!wpk系统是否存在透视行为(透视)wpk德州局怎么透视,教程策略(有挂教程)-哔哩哔哩该软...
透视辅助!epoker透视(透... 透视辅助!epoker透视(透视)约局吧开挂,教程举措(新版有挂)-哔哩哔哩该软件可以轻松地帮助玩家...