Android Kotlin

Saving & Reading Any Kind Of File Inside The Android Internal Storage

Google+ Pinterest LinkedIn Tumblr

Recently, I’ve been working on a survey-based application where the user collects data from different dealers around the city and upload it on the server. I know what you guys have been thinking right now! It’s a simple application just collect data and upload them. Yes, that’s what I thought when I start working on this project. But according to the client requirement, the application needs to store survey data when the user not connected to the internet.

Again it’s a simple task and I happily use the room persistence an SQLite library for data storage. But the main problem occurs when I got to know that the survey questionnaire may include video, audio, and file type questions.

We all know when developing Android application we’ve two options in order to store multimedia.

  • External Storage
  • Internal Storage

Now if I use the external storage option and store the multimedia inside it. Then there may be a chance user may delete data before uploading it on the server and my application crashes when trying to access that data. OK! not crash but the file may not be available for upload.

So, for the sake of transparency, I used the internal storage option and try to write the multimedia inside the application memory.

Note: The internal storage is only accessible to our own application. The application doesn’t need any kind of runtime permission from the user just to store files.

Now the question arises how do I store a different kind of multimedia inside my application memory. I cannot just copy the file and paste-like we do when we need to store any kind of file inside the external storage.

The solution is pretty much simple, we just need to read the content from the selected file as a ByteArray and write the bytes inside the newly created internal storage file.

Before showing you the code of how to store any kind of file inside the internal storage of android application here are some prerequisites:

  • You need to have the path of a file or selected file reference from which you want to store the content to your newly created internal storage file.
  • A unique name for internal storage file otherwise the file content will be overwritten.

Enough of this android internal storage intro let’s dive into the editor and see some code.

    private fun storeFileInInternalStorage(selectedFile: File, internalStorageFileName: String) {        
        val inputStream = FileInputStream(selectedFile) // 1
        val outputStream = application.openFileOutput(internalStorageFileName, Context.MODE_PRIVATE)  // 2
        val buffer = ByteArray(1024)
        inputStream.use {  // 3
            while (true) {  
                val byeCount =  // 4
                if (byeCount < 0) break
                outputStream.write(buffer, 0, byeCount)  // 5
            outputStream.close()  // 6

Here’s what going on inside the above code.

  1. Creates a FileInputStream by opening a connection to an actual file (the file, which content you want to store inside the internal storage memory).
  2. Opens a private file associated with the application context. The openFileOutput will create a new file if it doesn’t already exist. Also, make sure the file name internalStorageFileName cannot contain path separators.
  3. The use is actually an extension function. It executes the given lambda block function and closes the resources successfully whether an exception is thrown or not. In our case, it closes the stream.
  4. Reads the minimum 1024 bytes data from the selected file.
  5. Write the read bytes inside the newly created internal storage file.
  6. Close the output stream that we opened for the selected file.

Note: Don’t call the above method inside the MainThread. It’ll block the calling thread.

Testing the internal storage Method

So, we successfully created the utility method which read the contents from the selected file and writes the data inside the internal storage file. Let’s test the above method if we need to store the video file.

fun main() {
    val selectedVideoFilePath = 
    "/storage/emulated/0/DCIM/Camera/.bed1285d9cefce2c0351462547e3259f.mp4"  // 1
    val selectedVideoFile : File = File(selectedVideoFilePath)  // 2
    val selectedVideoFileExtension : String = selectedVideoFile.extension  // 3 
    val internalStorageVideoFileName : String = 
    UUID.randomUUID().toString().plus(selectedVideoFileExtension)  // 4
    storeFileInInternalStorage(selectedVideoFile, internalStorageVideoFileName)  // 5

Let’s go through the logic behind the above code:

  1. The path of the selected file.
  2. Creates a new file with a path because our method takes the instance of a selected file.
  3. Extract the extension from the selected file. The extension is must require because in order to create a new internal storage file we need to tell the extension of file explicitly.
  4. Like I said above the file name must be unique and I choose the UUID to create a file name for me and after that, I just concat the extension of the selected file.
  5. In the end, I just call the storeFileInInternalStorage method. And your video file is saved successfully.

Now let’s say I want to save a .xls format file inside the android internal storage. For this, we can happily use our storeFileInInternalStorage method.

fun main() {
    val studentExcelFilePath = 
    val studentExcelFile : File = File(studentExcelFilePath)  
    val studentExcelFileExtension : String = studentExcelFile.extension  
    val internalStorageExcelFileName : String = 
    storeFileInInternalStorage(studentExcelFile, internalStorageExcelFileName) 

You see we just need to change the selected file path everything else remains the same.

Reading files from internal Storage

You can get the reference of internally stored file with just one line of code.

val file : File = application.getFileStreamPath(internalStorageFilePath)

The getFileStreamPath returns a file on the filesystem where a file created with the openFileOutput method.

Alright, guys, this was my story of how do I store any kind of file inside the internal storage of Android application. If you have any suggestion or feedback with my method, please do comment below.

Thank you for being here and keep reading…

Write A Comment