1

I want to let user to pick up folder and my app will make a file in this folder. So I use Intent.ACTION_OPEN_DOCUMENT_TREE. Google says that I need to use DocumentFile instead of File. Previously I used File and want to get the result similar to result of code below

FileOutputStream fs = new FileOutputStream(mFile);
Writer writer = new BufferedWriter(new OutputStreamWriter(fs));
writer.append(mContent);

But DocumentFile is not a File and I can't use FileOutputStream. So I wrote this code using OutputStream

 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();

This code doesn't rewrite my file, but creates another one with name Note(1) So I want to know if there is a way to rewrite file using OutputStream or maybe another way using FileOutputStream, but I didn't get how to use it with DocumentFile.

Thank you in advance.

Valgaal
  • 896
  • 10
  • 25
  • Yes you are creating that file yourself. Remove that code. The file exists. So use `OutputStream out = getContentResolver().openOutputStream(data.getData()); `. You do not have too use anything of `DocumentFile` either. – greenapps Aug 15 '18 at 09:04
  • Oh, sorry , I forgot to mention that treeUri is a folder, not a file – Valgaal Aug 15 '18 at 09:07
  • 1
    Then use pickedDir.findFile() to see if the file exists. And use that uri. Only use createFIle() if the file does not exist otherwise you get another one as you have seen. findFile() will return null if the file does not exist. – greenapps Aug 15 '18 at 09:10
  • Ok, I did it like you said. But maybe there is another way without deletion.. – Valgaal Aug 15 '18 at 09:56
  • You should not delete. You should use its uri. I said that before. – greenapps Aug 15 '18 at 10:31

1 Answers1

9
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();
greenapps
  • 11,154
  • 2
  • 16
  • 19