Chapter 6. Files
As a developer, you might want to read, write, or inspect a file for any number of reasons. For example, you might want to modify an image and save it to disk, download a video to your user’s SD card (after determining if one is available), or use a simple indexed JSON flat-file database. File handling logic comes up frequently in application development, so a good grasp of the fundamentals is important for most developers.
Tasks
In this chapter, you’ll learn to:
-
Get properties from a file like size on disk or last modified date.
-
Read and write data to and from a file.
-
Copy data from one file to another.
Android
In Android, a developer might query the device for the location of an external SD on the device, compress a group of files for upload, write XML to track user preferences, get bitmaps from assets, read a resource file, or log out events in a persistent fashion. Even an SQLite database (the AOSP framework–provided database) exists as a single file, so you’d use the same logic to determine its size, or make a duplicate for export.
Reading and writing files in Java has come a long way, and modern versions of the language include streaming APIs, an updated package called java.nio.file (“nio” means “new input/output”), and some handy helper classes like Files and Paths that offer a variety of approaches to file system access. Unfortunately, these are not available to most Android developers, and at the time of this writing, only the most recent two ...