Search code examples
androidandroid-file

How to write and Read a text file with custom extension?


In my app, I am creating a file and writing some data to it using SAF. I ask the user to enter the name and then save some data to the file. Similarly, I let the user chose the file from storage and read some data from it. I want to do this with my custom file extension say ".xyz".

I found multiple sources with intent-filters, but what I know about intent filters is that they help you open the file with some app. I don't want to open my app when the file is clicked. I just want to access/read the file from within the app.

Presently when I am able to save the file with .xyz extension. But not able to read it. I have added following code in intent-filter

<data android:host="*" android:scheme="file" android:mimeType="text/plain" android:pathPattern=".*\\.xyz"/>

This is how I am reading the file:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/*");
startActivityForResult(intent, READ_REQUEST_CODE);

When the file explorer opens for selecting files for reading, the target extension .xyz files come blurred.


Solution

  • Replace text/* with */*.

    Android does very little with custom file extensions, just as the Web does very little with custom file extensions. In particular, since Android has no MIME type for a custom file extension, text/* will not match it.