Accessing the Internal File System

Android runs Linux under the covers, so there's a real file system mounted in there with a root directory and everything. The files are stored on nonvolatile flash memory built into the device, so they are not lost when the phone is turned off.

All of the usual Java file I/O routines from the package are available for your program to use, with the caveat that your process has limited permissions so it can't mess up any other application's data. In fact, the main thing it can access is a package private directory created at install time (/data/data/packagename).

A few helper methods are provided on the Context class (and thus on the Activity class extended by each of your activities) to let you read and write data there. Here are the ones you're most likely to need:

deleteFile() Delete a private file. Returns true if it worked, false otherwise.

fileList() Return a list of all files in the application's private area in a String array. openFileInput( ) Open a private file for reading. Returns a openFileOutput() Open a private file for writing. Returns a

However, since this internal memory is limited, I recommend you keep the size of any data you put there low, say a megabyte or two at the most, and carefully handle I/O errors when writing in case the space runs out.

Luckily, internal memory isn't the only storage that you have to work with.

Report erratum

All in the Family

If you recall from Section 2.5, Safe and Secure, on page 40, each application normally gets its own user ID at install time. That user ID is the only one that is allowed to read and write from the application's private directory. However, if two applications are signed* by the same digital certificate, then Android assumes they are from the same developer and gives them the same user ID.

On the one hand, that allows them to share all sorts of data with each other if they so choose. But on the other, it also means they'll need to take special care to stay out of each other's way.


0 0

Post a comment