Scoped Storage: Loading, Saving, and Deleting (internal storage)

Vijay Mishra
The Android Cafe
Published in
3 min readSep 19, 2021

--

Hello Guys, Welcome to the second part of the series scoped storage. In this part, we will see how we can use internal operations for saving, loading, and deleting a file from internal storage.

In case you have missed the first part. 😀

Saving Files

Let’s start by looking at how to save any file to internal storage.

In the above function, we are trying to save bitmap to internal storage. Let’s break this function into two parts.

  1. openFileOutput: Opens a private file associated with this Context’s application package for writing. Creates the file if it doesn’t already exist.
  2. use: Is an extension function that is used to execute the given block function on this resource and then closes it down correctly whether an exception is thrown or not.

In brief, after the openFileOutput opens a stream to write into we use the “use” extension function to access the stream and use it because it is important to close the stream after writing to avoid any IOException. It is that easy.

There is one thing to keep in mind though that all the files that you store in internal storage will be deleted after the application gets uninstalled from the device.

Load Files

We will now be loading all the files from the internal storage.

In the above example, we have loaded all the images having “.jpg” format from internal storage. We will break the function into 2 parts.

  1. suspend: I have made the function a suspend function because it will do all the IO operations and I don’t want to perform IO operation on the main thread.
  2. filesDir: Returns the absolute path to the directory on the filesystem where files created with openFileOutput are stored.

In Brief, The above function will get executed in a coroutines scope to fetch all the files from internal storage that are listed by method listFiles is then filtered for files that have “.jpg” extension and returns the list of bitmap.

No additional permissions are required for the calling app to read or write files under the returned path.

Delete Files

Now Let’s see how we can delete the files.

Deleting the file is by far the easiest of all three. Sorry guys, this time we could not break it into 2 parts 🙃. This function is fairly simple to explain we only need to call the deleteFile and pass the filename to the function. It returns a boolean variable depending on the status of the delete process.

That’s all for this part, hope it helped you. If it did show some love by 👏 and follow for more such content. See you in the next part when we will discuss External storage. Till then✌, stay safe and wear 😷.

--

--