Read a json/text file from assets folder

We can add any file to be incorporated in android project in assets folder, located at ‘/app/src/main/assets/’ and then open it in the android app using InputStream.

Here we will learn how to read the contents of a file in assets folder as a String and display it in a TextView.

Step 1: Add a TextView textview1, inside a vertical ScrollView.

Step 2: Add the text file (e.g. emoji_transport.json) inside the assets folder of your project.

Step 3: Add following code in onCreate event:

try {

java.io.InputStream stream = getAssets().open("emoji_transport.json");

java.io.BufferedReader bfr = new java.io.BufferedReader(new java.io.InputStreamReader(stream));

String nextline = "";
String allText = "";

while ( (nextline = bfr.readLine()) != null) {
allText = allText + nextline + "\n";
}

textview1.setText(allText);
} catch (java.io.IOException e){
showMessage(e.toString());
}

Step 4: Save and run the project. It will display the contents of the file in textview1.

Leave a Reply