How to create multiple files at once using android Storage Access Framework

1k Views Asked by At

Before scoped storage app could create set of files like this

if(isStoragePermissionGranted()){
val textFileDir = File(Environment.getExternalStorageDirectory(), getString(R.string.app_name)+"/"+"Textfiles/")
textFileDir.mkdir()
    for(i in 0 until 5){
        val textfile = File(textFileDir, String.format("%s-%s.txt", "TextFile", i))
        textfile.writeText("Content")
    }
}

But with the scoped storage every file that we create has to be given permission separately

const val CREATE_FILE = 1

private fun createFile(pickerInitialUri: Uri) {
    val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "text/plain"
        putExtra(Intent.EXTRA_TITLE, "invoice.txt")

        putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
    }
    startActivityForResult(intent, CREATE_FILE)
}

How can we create set of text files and writing content to them at once without giving permission one by one using access storage framework.

1

There are 1 best solutions below

0
On

This is how i was able to create multiple files. I followed @Commonsware suggestion

public void selectDirectory(Uri uriToLoad) {
// Choose a directory using the system's file picker.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);

// Optionally, specify a URI for the directory that should be opened in
// the system file picker when it loads.
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uriToLoad);

startActivityForResult(intent, your-request-code);
}



public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == your-request-code) {
        if (data != null) {
            Uri uri = data.getData();
            
            DocumentFile outputFolder = DocumentFile.fromTreeUri(getActivity(), uri);

          for(int i=0;i<5; i++){
            DocumentFile documentFileNewFile = outputFolder.createFile("application/random",
            filename + ".txt");
           OutputStream fos = getActivity().getContentResolver().openOutputStream(documentFileNewFile.getUri());
          someMethodToWriteToOutputStream(fos);
         }

        }
    }
   }