The aim of this article is to show users how to use internal storage. In this article will be creating an application that can write data to a file and store it in internal storage and read data from the file and display it on the main activity using TextView. Saving and loading data on the internal storage is private for an application that can not be accessed by other applications. When the app is uninstalled the data stored in the internal by that app is removed. To read and write in the android internal storage we have two methods
- OpenFileOutput(): used for creating and saving a file. This method returns a FileOutputStream instance.
Syntax: OpenFileOutput(String filename,int mode)
Context.MODE_PRIVATE: If the file exists then it is overiddent else a new file is created.
Context.MODE_APPEND: if the file exists then the data is appended at the end of the file.
- OpenFileInput(): Used to read data from a file, this returns an FileInputStream instance.
Syntax: OpenFileInput( String filename)
A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
The activity_main.xml file has the following widgets
- One EditText for accepting user input
- Two Buttons one for reading data and the other for writing
- One TextView to display the content of the file
Below is the code for the activity_main.xml file.
Step 3: Working with the MainActivity.java file
Inside the MainActivity.java file we are going to do the following things:
The file will be creating is DemoFile.txt. this can be found in Device File Explorer > data > data > application_package > files
Read and Write methods:
The following method is used to read data from the internal data.
The method used for creating a file and writing data to internal storage.
Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.