Read a simple text file

Asked 2 years ago, Updated 2 years ago, 78 views

You want to simply read a text file from a sample Android application. I'm currently using the code written below.

1. InputStream inputStream = openFileInput("test.txt");
2. InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
3. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

What I'm curious about is where to place the "text.txt" file within the project. I put the file under the "res/raw" and "asset" folders, but if I execute the above code, the "FileNotFound" exception occurs from the first line.

I'd appreciate your help.

android java-io text-file

2022-09-22 08:16

1 Answers

Place the text file in the /assets directory within the Android project. And use AssetManager to access files.

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

Alternatively, you can place it in the /res/raw directory. Then you can access and find the file through the R file.

InputStream is = context.getResources().openRawResource(R.raw.test);


2022-09-22 08:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.