How to Read a Text File in Android?
A text file is a type of file that can store a sequence of characters or text. These characters can be anything that is human-readable. Such kind of files does not have any formatting for the text like Bold, Italics, Underline, Font, Font Size, etc. A Text file in Android can be used for accessing or reading the information or text present in it. Meaning, information could be stored in a text file and could be accessed whenever required in the run-time. So, through this article, we will show you how you could read or fetch text from a text file in Android.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Create an asset folder
Please refer to Assets Folder in Android Studio to create an assets folder in Android Studio. We shall be creating a text file in the assets folder.
Step 3: Create a text file in the asset folder
We can create a text file by simply right-clicking on the assets folder, drag the mouse on new, and click on File. Now type in some desired name, add “.txt” extension, and press Enter. Another way of doing the same is creating a text file on Desktop and simply copying it into the assets folder. This is how our text file looks like:
GeeksforGeeks A computer science portal for geeks
Step 4: Add a TextView in the layout file (activity_main.xml)
We will add a TextView in the layout to display the text from the text file.
Step 5: Write the below program in the main code (MainActivity.kt)
In the main code, we will be reading the text file and displaying the text from this file in the TextView. Please refer to the comments available at almost every line of code for better understanding.
As soon as the application launches, we can see that the text from the text file is displayed in the TextView.