javaandroidurioutputstreamdocumentfile

How to rewrite DocumentFile


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.


Solution

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