How to access a text file from an android Application?

945 views Asked by At

I have a text file with some data that I want to copy in an SQLite database. I can not access to files on "downloads" directory of the phone I have an Permission denied exception (I use the path provided by the Device File Explorer of Android-Studio-3.1.4 that allows me to create a file, get its path, edit the content but not saving it!).
Some forums tells that I have to put the file on data/data/app-name but I technically failed to do that.
I tried to create a new file in my project, but still I do not know how to access it with code.

    FileInputStream file = new FileInputStream("/storage/self/primary/Download/file.txt"));

before this line I tried to add:

    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

But this is not the solution.
So where should I put the file? what will be the right path? and what are the required permissions that I should add in the manifest? thanks.

3

There are 3 answers

0
P Vartak On

Before accessing any file from storage you need permission.

For Reading : <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

For Writing : <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> (Read permission is explicitly granted for this permission)

Also, you need to request those permission at runtime on device running Android M and Above.

Check following link : https://developer.android.com/training/permissions/requesting

0
Andreas K. aus M. On

This question is partially a duplicate of [https://stackoverflow.com/questions/2902689/how-can-i-read-a-text-file-from-the-sd-card-in-android/]. In particular Google, beginning with Android 11, discourages any app from opening text or database files at all, except in the app's private directories. One workaround is to copy the file to the app's private directory, using SAF (this is extremely slow, about factor 1/100), and then open it there, using standard File datatype.

0
Krishnapal Sendhav On

If you want to access you phones download folder /storage/emulated/0/Download/ this is the path for that. or if you only want to access text file from you phone storage use file_picker plugin. For this you have to add permission in your AndroidManifest.xml file

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>

Use this method for accessing file

FilePickerResult? result = await FilePicker.platform.pickFiles(type:FileType.custom,allowedExtensions:['txt']);