Home > Back-end >  Edit a text file saved in a shared storage
Edit a text file saved in a shared storage

Time:11-08

We have successfully created a text file using the below code:

val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "text/plain"
                putExtra(Intent.EXTRA_TITLE, "logDebug.txt")
            }
            createDebugLogFileIntent.launch(intent)

We are getting the URI from the result as below:

private val createDebugLogFileIntent =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult? ->
        val uri = result?.data?.data
            val contentResolver = appContext().contentResolver
            val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            // Check for the freshest data.
            uri?.let { contentResolver.takePersistableUriPermission(it, takeFlags) }
    }

The URI is as below:

content://com.android.providers.downloads.documents/document/22949

The uri?.path call gives the path as below:

/document/22949

We save the uri?.path into a sharedPreferences as debugLogFilePath String.

After that, we are trying to edit the text file as below:

Java code:

File debugLogFile = new File(debugLogFilePath);
            String newLine = "\n\r";
            String currentDateTime = new LocalDateTime().toString();
            content =
                    newLine   " Current Local Date Time: "   currentDateTime   " Android OS: "   Build.VERSION.SDK_INT
                              " : "   content;
            FilesKt.appendText(debugLogFile, content, StandardCharsets.UTF_8);

It gives us the exception:

open failed: ENOENT (No such file or directory)

We have tried the following solution as given on the official site:

private void alterDocument(Uri uri) {
    try {
        ParcelFileDescriptor pfd = getActivity().getContentResolver().
                openFileDescriptor(uri, "w");
        FileOutputStream fileOutputStream =
                new FileOutputStream(pfd.getFileDescriptor());
        fileOutputStream.write(("Overwritten at "   System.currentTimeMillis()  
                "\n").getBytes());
        // Let the document provider know you're done by closing the stream.
        fileOutputStream.close();
        pfd.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

However, we got the same exception.

CodePudding user response:

To use the uri obtained from ACTION_CREATE_DOCUMENT just open an output stream or input stream for it.

OutputStream os = getContentResolver().openOutputStream(uri);

Now you can write to the stream.

  • Related