Saving and reading files in the internal storage

You can save and read files in the internal storage as private files which only your app can see except for other apps with root privileges.
The absolute path of this folder is data\data\[your app package]\files
The class Context provides some methods which help you to make operations such as:

  • openFileInput(String name) Open a private file associated with this Context’s application package for reading
  • openFileOutput(String name, int mode) Open a private file associated with this Context’s application package for writing
  • getFilesDir() Gets the absolute path to the filesystem directory where your internal files are saved
  • getDir() Creates (or opens an existing) directory within your internal storage space
  • deleteFile() Deletes a file saved on the internal storage
  • fileList() Returns an array of files currently saved by your application

and you don’t need to have special permissions in order to use these methods.

For example the following code taken from Using the Internal Storage creates a file containing the string “hello world!”

where at the line 5, in place of MODE_PRIVATE you can use MODE_APPEND, other constants such as MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE are deprecated.

The following code reads the same file and shows a message with the text “hello world!”

But these examples have a limitation: they can’t be used in sub folders, in other words you can’t create a tree structure of directories and files.
If you need to create files in subdirectories you must use the standard technique of java, for example the following code creates a file inside the folder “sub”

and the following code reads the same file

One Reply to “Saving and reading files in the internal storage”

  1. I don’t understand why I keep getting the same message: “error: cannot find symbol method getApplicationContext()” no matter what examples I choose. What do I need to eliminate it? Thank you for your answer!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.