首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何重写DocumentFile

如何重写DocumentFile
EN

Stack Overflow用户
提问于 2018-08-15 16:12:31
回答 1查看 1.1K关注 0票数 1

我想让用户拿起文件夹,我的应用程序将在此文件夹中创建一个文件。所以我使用Intent.ACTION_OPEN_DOCUMENT_TREE。谷歌说我需要使用DocumentFile而不是文件。之前我使用的是File,希望得到的结果与下面的代码结果类似

代码语言:javascript
复制
FileOutputStream fs = new FileOutputStream(mFile);
Writer writer = new BufferedWriter(new OutputStreamWriter(fs));
writer.append(mContent);

但是DocumentFile不是文件,我不能使用FileOutputStream。所以我用OutputStream写了这段代码

代码语言:javascript
复制
 Uri treeUri = data.getData();
 DocumentFile pickedDir = DocumentFile.fromTreeUri(MainActivity.this, treeUri);
 DocumentFile mFile = pickedDir.createFile("text/plain", "Note");
 OutputStream out = getContentResolver().openOutputStream(mFile.getUri());                                            
 out.write(infos.get(i).getContent().getBytes());
 out.flush();
 out.close();

这段代码没有重写我的文件,但创建了另一个名称为Note(1)的文件,所以我想知道是否有一种方法可以使用OutputStream重写文件,或者使用FileOutputStream重写文件,但我不知道如何在DocumentFile中使用它。

提前谢谢你。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-15 18:30:23

代码语言:javascript
复制
Uri treeUri = data.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(MainActivity.this, treeUri);
DocumentFile documentFile = pickedDir.findFile("Note");
if (documentFile == null) 
  documentFile = pickedDir.createFile("text/plain", "Note");

OutputStream out = getContentResolver().openOutputStream(documentFile.getUri());                                            
out.write(infos.get(i).getContent().getBytes());
out.flush();
out.close();
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51855122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档