Javatpoint Logo
Javatpoint Logo

Kotlin Android Read and Write External Storage

Android External Storage is the memory space in which we perform read and write operation. Files in the external storage are stored in /sdcard or /storage folder etc. The files which are saved in the external storage is readable and can be modified by the user.

Before accessing the file in external storage in our application, we should check the availability of the external storage in our device.

Write to File in External Storage

The java.io package offers openFileOutput() method which returns the instance of FileOutputStream class to write the file in external storage of the device. To acquire a directory that's used by only your app by calling getExternalFilesDir(). To write the data into the file call the FileOutputStream .write() method.

Read File content from External Storage

The java.io package offers openFileInput() method which returns the instance of FileInputStream class and read the file from the external storage of the device. To read the data from file call the BufferedReader().readLine().

External Storage Access Permission

Add the following permission in AndroidManifest.xml file.

Kotlin Android Read and Write External Storage Example

In this example, we will write the data to file inside the external storage and read the same file content from same external storage.

activity_main.xml

Add the following code in the activity_main.xml file. In this file, add two EditText for input file name, file content and two Button for saving and view file content.

MainActivity.kt

Add the following code in the MainActivity.kt class. In this class, we are saving the file name and data inside external storage by clicking the save button and retrieving the file content by clicking the view button.

AndroidManifest.xml

Output:

Kotlin Android Read and Write External Storage Kotlin Android Read and Write External Storage
Kotlin Android Read and Write External Storage Kotlin Android Read and Write External Storage
Next Topic#




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA