Reading and Writing Files in Internal and External Storage
In Chapter: Data Persistence
Author: Ian Darwin ('idarwin')
Files can be created and accessed in several different places on the device, notably, application private data and "sd-card" style data. You need to learn the APIs for dealing with these sections of the filesystem.
Use the Context methods openFileInput()
for "internal" storage. Use Context.getExternalFilesDir() or Environment.getExternalStoragePublicDirectory() for shared storage.
While every Android device features a fairly complete Unix/Linux file system hierarchy, parts of it are "off-limits" for normal applications, to ensure that the device's integrity and functionality are not compromised. Storage available for reading/writing within the application are divided into "internal" storage, private per-application, and "public" storage, which may be accessed by other applications.
The "internal" or private data area, which is always present and is actually under /data/data/PKGNAME/, can be accessed using the Context methods openFileInput(String filename), which returns a FileInputStream object, or openFileOutput(String filename, int mode), which returns a FileOutputStream. The mode value should either be zero for a new file, or Context.MODEAPPEND to add to the end of an existing file. Other mode values are deprecated and should not be used.
Once obtained, these Streams can be read using standard java.io classes and methods, e.g., wrap the FileInputStream in an InputStreamReader and a BufferedReader to get line-at-a-time access to character data. You should close these when finished with them.
The external storage is, predictably, more complicated. The mental model of external storage is a removable flash-memory card such as an SD&tm; card. Initially most devices had an SD-Card or MicroSD-Card slot. Today most do not, but some still do. So Android always treats the /sdcard as though it might be removable, or might be present but the write-protect switch might be enabled. You should not access it by this directory name, but through the API calls.
So first, you have to check if the external storage is even available. The method static String Environment.getExternalStorageState() returns one of almost a dozen String values, but unless you are writing a File Manager type application, you only care about two: MEDIAMOUNTED and MEDIAMOUNTEDREADONLY; any other values imply that the external storage directory is not currently usable.
XXX More here, and code examples, to follow.