0

在范围存储应用程序可以创建这样的文件集之前

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")
    }
}

但是对于范围存储,我们创建的每个文件都必须单独授予权限

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)
}

我们如何使用访问存储框架在不逐个授予权限的情况下创建一组文本文件并将内容写入它们。

4

1 回答 1

0

这就是我能够创建多个文件的方式。我遵循了@Commonsware 的建议

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

        }
    }
   }





 
于 2021-12-07T13:56:51.930 回答