The tutorial app has two Activities.
The first Activity saves the files and the second reads the files, displaying the result.
Reading files from external storage
Here’s the code to read the file that was saved in the Pictures directory of the external storage.
We first check if the storage is available and then if the file exists. If either is false, we can’t continue.
If the file exists, it is decoded and displayed in an image view.
Note the following:
- getExternalStorageState() – use it to check if the external storage is available. If it’s not available then we can’t proceed
- getExternalStoragePublicDirectory() – gets the external public directory
- Environment.DIRECTORY_PICTURES – gets the Pictures directory where our file is saved
- File – creates an instance of our file, MyCachedImage.jpg
- filePicture.exists() – checks if our file exists in the Pictures directory
- BitmapFactory.decodeFile() – decodes the file, creating a Bitmap
- ImageView.setVisibility() – makes sure that the image view is visible
- setImageBitmap() – displays the image
Reading files from internal storage
Here’s the code to read the text file.
Note the following:
- this – application context
- openFileInput() – opens the private file (our text file) associated with the context’s application package
- FileInputStream – an input stream that reads bytes from the file
- BufferedReader – buffers the bytes read by the input stream. This increases performance because later we build the string by accessing the buffer rather than repeatedly reading the input stream
- StringBuilder – enables the building of strings using modifiable sequences of characters
- While loop – we use the loop to read each line of text in the buffer and append it to our StringBuilder object, finalString
- setVisibility() – ensures that the text view is visible
- setText() – sets the text to display in the text view
- finalString.toString() – converts the StringBuilder object to a String object
- try/catch – gracefully handles any problems in reading the file so that the app won’t crash
Reading files from the Cache
Here’s the code for reading the cache file. Note the following:
- this - application context
- getCacheDir() - gets the absolute path to the cache directory for this application
- getPath() – gets the path for the file
- File – create a File for the given path
- myCachedFile.exists() – checks if the file that we created actually exists
- BitmapFactory.decodeFile() – decodes the file, creating a Bitmap
- ImageView.setVisibility() – makes sure that the image view is visible
- setImageBitmap() – displays the image
You may also be interested in our Firebase tutorial, Using a Firebase Realtime Database in your app
The tutorial application was created using Android Studio. You can download the project files here