Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Reading a Text File

I am making a project in Android Studio, I have a text file in my project folder, each time I compile, I want my code to read that .txt file. When everythings finished, I want that .txt file to be inside .apk file. I am not trying to read from SD card etc.

But I am getting "File not found Exception" each time I compile. While using eclipse, when you place the .txt file in same directory as your project, code can find .txt file without problems but in Android Studio, it cannot find text file I just created. Where do I have to place my .txt file inside my project folder?
Here is the code:

FileReader in = new FileReader("TEXTgreetingKeywords.txt"); 
final BufferedReader br = new BufferedReader(new InputStreamReader(in));

I used to same method to read text file in Java. I don't understand why it isn't working on Android since it uses Java too.

EDIT------

I used asset manager but I got the same error again

AssetManager asset = getAssets();
    try {
         in = asset.open("text.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }

Do I have to change the directory to something like "C:\App\main\text.txt" ?

like image 698
berkc Avatar asked Oct 30 '22 23:10

berkc


1 Answers

Read Text file From Assets:

Create raw folder in Resources directory:

Paste your file in raw folder:

Read text from file:

private String readText() {
        InputStream inputStream = getResources().openRawResource(
                R.raw.license_agreement);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int i;
        try {
            i = inputStream.read();
            while (i != -1) {
                byteArrayOutputStream.write(i);
                i = inputStream.read();
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toString();
    }

Hope it will help you.

like image 188
Hiren Patel Avatar answered Nov 09 '22 05:11

Hiren Patel