Industrial Training




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.


var myExternalFile:File = File(getExternalFilesDir(filepath),fileName)  
 try {  
     val fileOutPutStream = FileOutputStream(myExternalFile)  
     fileOutPutStream.write(fileContent.toByteArray())  
     fileOutPutStream.close()  
 } catch (e: IOException) {  
     e.printStackTrace()  
 }  
var myExternalFile:File = File(getExternalFilesDir(filepath),fileName)  
 try {  
     val fileOutPutStream = FileOutputStream(myExternalFile)  
     fileOutPutStream.write(fileContent.toByteArray())  
     fileOutPutStream.close()  
 } catch (e: IOException) {  
     e.printStackTrace()  
 }  

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().


var myExternalFile:File = File(getExternalFilesDir(filepath), fileName)  
val filename = fileName.text.toString()  
myExternalFile = File(getExternalFilesDir(filepath),filename)   
    var fileInputStream =FileInputStream(myExternalFile)  
    var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)  
    val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)  
    val stringBuilder: StringBuilder = StringBuilder()  
    var text: String? = null  
    while ({ text = bufferedReader.readLine(); text }() != null) {  
        stringBuilder.append(text)  
    }  
    fileInputStream.close()  
var myExternalFile:File = File(getExternalFilesDir(filepath), fileName)  
val filename = fileName.text.toString()  
myExternalFile = File(getExternalFilesDir(filepath),filename)   
    var fileInputStream =FileInputStream(myExternalFile)  
    var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)  
    val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)  
    val stringBuilder: StringBuilder = StringBuilder()  
    var text: String? = null  
    while ({ text = bufferedReader.readLine(); text }() != null) {  
        stringBuilder.append(text)  
    }  
    fileInputStream.close()  

External Storage Access Permission


Add the following permission in AndroidManifest.xml file.


< uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>  
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
< uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>  
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

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.


< ?xml version="1.0" encoding="utf-8"?>  
< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.kotlinexternalstoragereadwrite.MainActivity">  
  
  
    < TextView  
        android:id="@+id/textView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignLeft="@+id/textView2"  
        android:layout_alignParentTop="true"  
        android:layout_alignStart="@+id/textView2"  
        android:layout_marginTop="68dp"  
        android:text="File Name"  
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintHorizontal_bias="0.027"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toTopOf="parent"  
        app:layout_constraintVertical_bias="0.065" />  
  
    < TextView  
        android:id="@+id/textView2"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignBottom="@+id/editTextData"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentStart="true"  
        android:layout_marginBottom="36dp"  
        android:layout_marginLeft="50dp"  
        android:layout_marginStart="50dp"  
        android:text="File Data"  
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintHorizontal_bias="0.027"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@+id/textView"  
        app:layout_constraintVertical_bias="0.167" />  
  
    < EditText  
        android:id="@+id/editTextFile"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignLeft="@+id/editTextData"  
        android:layout_alignStart="@+id/editTextData"  
        android:layout_alignTop="@+id/textView"  
        android:ems="10"  
        android:inputType="none" />  
  
    < EditText  
        android:id="@+id/editTextData"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentEnd="true"  
        android:layout_alignParentRight="true"  
        android:layout_below="@+id/editTextFile"  
        android:layout_marginEnd="37dp"  
        android:layout_marginRight="37dp"  
        android:layout_marginTop="30dp"  
        android:ems="10"  
        android:inputType="none"  
        android:lines="5" />  
  
    < Button  
        android:id="@+id/button_save"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentBottom="true"  
        android:layout_marginBottom="68dp"  
        android:layout_toLeftOf="@+id/editTextData"  
        android:layout_toStartOf="@+id/editTextData"  
        android:text="Save" />  
  
    < Button  
        android:id="@+id/button_view"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignBottom="@+id/button_save"  
        android:layout_alignEnd="@+id/editTextData"  
        android:layout_alignRight="@+id/editTextData"  
        android:layout_marginEnd="43dp"  
        android:layout_marginRight="43dp"  
        android:text="View" />  
  
 < /RelativeLayout>  
< ?xml version="1.0" encoding="utf-8"?>  
< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.kotlinexternalstoragereadwrite.MainActivity">  
  
  
    < TextView  
        android:id="@+id/textView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignLeft="@+id/textView2"  
        android:layout_alignParentTop="true"  
        android:layout_alignStart="@+id/textView2"  
        android:layout_marginTop="68dp"  
        android:text="File Name"  
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintHorizontal_bias="0.027"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toTopOf="parent"  
        app:layout_constraintVertical_bias="0.065" />  
  
    < TextView  
        android:id="@+id/textView2"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignBottom="@+id/editTextData"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentStart="true"  
        android:layout_marginBottom="36dp"  
        android:layout_marginLeft="50dp"  
        android:layout_marginStart="50dp"  
        android:text="File Data"  
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintHorizontal_bias="0.027"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@+id/textView"  
        app:layout_constraintVertical_bias="0.167" />  
  
    < EditText  
        android:id="@+id/editTextFile"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignLeft="@+id/editTextData"  
        android:layout_alignStart="@+id/editTextData"  
        android:layout_alignTop="@+id/textView"  
        android:ems="10"  
        android:inputType="none" />  
  
    < EditText  
        android:id="@+id/editTextData"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentEnd="true"  
        android:layout_alignParentRight="true"  
        android:layout_below="@+id/editTextFile"  
        android:layout_marginEnd="37dp"  
        android:layout_marginRight="37dp"  
        android:layout_marginTop="30dp"  
        android:ems="10"  
        android:inputType="none"  
        android:lines="5" />  
  
    < Button  
        android:id="@+id/button_save"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentBottom="true"  
        android:layout_marginBottom="68dp"  
        android:layout_toLeftOf="@+id/editTextData"  
        android:layout_toStartOf="@+id/editTextData"  
        android:text="Save" />  
  
    < Button  
        android:id="@+id/button_view"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignBottom="@+id/button_save"  
        android:layout_alignEnd="@+id/editTextData"  
        android:layout_alignRight="@+id/editTextData"  
        android:layout_marginEnd="43dp"  
        android:layout_marginRight="43dp"  
        android:text="View" />  
  
< /RelativeLayout>  

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.


package example.javatpoint.com.kotlinexternalstoragereadwrite  
  
import android.support.v7.app.AppCompatActivity  
import android.os.Bundle  
import android.view.View  
import android.widget.Button  
import android.widget.EditText  
import android.widget.Toast  
import android.os.Environment  
import java.io.*  
  
class MainActivity : AppCompatActivity() {  
    private val filepath = "MyFileStorage"  
    internal var myExternalFile: File?=null  
    private val isExternalStorageReadOnly: Boolean get() {  
        val extStorageState = Environment.getExternalStorageState()  
        return if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  
                true  
        } else {  
                false  
        }  
    }  
    private val isExternalStorageAvailable: Boolean get() {  
        val extStorageState = Environment.getExternalStorageState()  
        return if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  
            true  
        } else{  
            false  
        }  
    }  
  
    override fun onCreate(savedInstanceState: Bundle?) {  
        super.onCreate(savedInstanceState)  
        setContentView(R.layout.activity_main)  
        val fileName = findViewById(R.id.editTextFile) as EditText  
        val fileData = findViewById(R.id.editTextData) as EditText  
        val saveButton = findViewById< Button>(R.id.button_save) as Button  
        val viewButton = findViewById(R.id.button_view) as Button  
  
        saveButton.setOnClickListener(View.OnClickListener {  
           myExternalFile = File(getExternalFilesDir(filepath), fileName.text.toString())  
            try {  
                val fileOutPutStream = FileOutputStream(myExternalFile)  
                fileOutPutStream.write(fileData.text.toString().toByteArray())  
                fileOutPutStream.close()  
            } catch (e: IOException) {  
                e.printStackTrace()  
            }  
            Toast.makeText(applicationContext,"data save",Toast.LENGTH_SHORT).show()  
        })  
        viewButton.setOnClickListener(View.OnClickListener {  
           myExternalFile = File(getExternalFilesDir(filepath), fileName.text.toString())  
  
           val filename = fileName.text.toString()  
           myExternalFile = File(getExternalFilesDir(filepath),filename)  
           if(filename.toString()!=null && filename.toString().trim()!=""){  
               var fileInputStream =FileInputStream(myExternalFile)  
               var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)  
               val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)  
               val stringBuilder: StringBuilder = StringBuilder()  
               var text: String? = null  
               while ({ text = bufferedReader.readLine(); text }() != null) {  
                   stringBuilder.append(text)  
               }  
               fileInputStream.close()  
               //Displaying data on EditText  
               Toast.makeText(applicationContext,stringBuilder.toString(),Toast.LENGTH_SHORT).show()  
           }  
        })  
  
        if (!isExternalStorageAvailable || isExternalStorageReadOnly) {  
            saveButton.isEnabled = false  
        }  
    }  
}  
package example.javatpoint.com.kotlinexternalstoragereadwrite  
  
import android.support.v7.app.AppCompatActivity  
import android.os.Bundle  
import android.view.View  
import android.widget.Button  
import android.widget.EditText  
import android.widget.Toast  
import android.os.Environment  
import java.io.*  
  
class MainActivity : AppCompatActivity() {  
    private val filepath = "MyFileStorage"  
    internal var myExternalFile: File?=null  
    private val isExternalStorageReadOnly: Boolean get() {  
        val extStorageState = Environment.getExternalStorageState()  
        return if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  
                true  
        } else {  
                false  
        }  
    }  
    private val isExternalStorageAvailable: Boolean get() {  
        val extStorageState = Environment.getExternalStorageState()  
        return if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  
            true  
        } else{  
            false  
        }  
    }  
  
    override fun onCreate(savedInstanceState: Bundle?) {  
        super.onCreate(savedInstanceState)  
        setContentView(R.layout.activity_main)  
        val fileName = findViewById(R.id.editTextFile) as EditText  
        val fileData = findViewById(R.id.editTextData) as EditText  
        val saveButton = findViewById< Button>(R.id.button_save) as Button  
        val viewButton = findViewById(R.id.button_view) as Button  
  
        saveButton.setOnClickListener(View.OnClickListener {  
           myExternalFile = File(getExternalFilesDir(filepath), fileName.text.toString())  
            try {  
                val fileOutPutStream = FileOutputStream(myExternalFile)  
                fileOutPutStream.write(fileData.text.toString().toByteArray())  
                fileOutPutStream.close()  
            } catch (e: IOException) {  
                e.printStackTrace()  
            }  
            Toast.makeText(applicationContext,"data save",Toast.LENGTH_SHORT).show()  
        })  
        viewButton.setOnClickListener(View.OnClickListener {  
           myExternalFile = File(getExternalFilesDir(filepath), fileName.text.toString())  
  
           val filename = fileName.text.toString()  
           myExternalFile = File(getExternalFilesDir(filepath),filename)  
           if(filename.toString()!=null && filename.toString().trim()!=""){  
               var fileInputStream =FileInputStream(myExternalFile)  
               var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)  
               val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)  
               val stringBuilder: StringBuilder = StringBuilder()  
               var text: String? = null  
               while ({ text = bufferedReader.readLine(); text }() != null) {  
                   stringBuilder.append(text)  
               }  
               fileInputStream.close()  
               //Displaying data on EditText  
               Toast.makeText(applicationContext,stringBuilder.toString(),Toast.LENGTH_SHORT).show()  
           }  
        })  
  
        if (!isExternalStorageAvailable || isExternalStorageReadOnly) {  
            saveButton.isEnabled = false  
        }  
    }  
}  

AndroidManifest.xml


< ?xml version="1.0" encoding="utf-8"?>  
< manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="example.javatpoint.com.kotlinexternalstoragereadwrite">  
    < uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>  
    < uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
    < application  
        android:allowBackup="true"  
        android:icon="@mipmap/ic_launcher"  
        android:label="@string/app_name"  
        android:roundIcon="@mipmap/ic_launcher_round"  
        android:supportsRtl="true"  
        android:theme="@style/AppTheme">  
        < activity android:name=".MainActivity">  
            < intent-filter>  
                < action android:name="android.intent.action.MAIN" />  
  
                < category android:name="android.intent.category.LAUNCHER" />  
            < /intent-filter>  
        < /activity>  
    < /application>  
  
< /manifest>  
< ?xml version="1.0" encoding="utf-8"?>  
< manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="example.javatpoint.com.kotlinexternalstoragereadwrite">  
    < uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>  
    < uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
    < application  
        android:allowBackup="true"  
        android:icon="@mipmap/ic_launcher"  
        android:label="@string/app_name"  
        android:roundIcon="@mipmap/ic_launcher_round"  
        android:supportsRtl="true"  
        android:theme="@style/AppTheme">  
        < activity android:name=".MainActivity">  
            < intent-filter>  
                < action android:name="android.intent.action.MAIN" />  
  
                < category android:name="android.intent.category.LAUNCHER" />  
            < /intent-filter>  
        < /activity>  
    < /application>  
  
< /manifest>  

Output:



Hi I am Pluto.