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:

  1. Get properties from a file like size on disk or last modified date.

  2. Read and write data to and from a file.

  3. 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 ...

Get Native Mobile Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.