It's good practice to use Shared Preferences or a database to store your application data, but there are still times when you'll want to use files directly rather than rely on Android's managed mechanisms.
As well as the standard Java I/O classes and methods, Android offers openFileInput and openFileOuput to simplify reading and writing streams from and to local files, as shown in Listing 6-8.
LISTING 6-8: Saving and loading files Available for download on String FILE_NAME = "tempfile.tmp"; Wrox.com
// Create a new output file stream that's private to this application. FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE); // Create a new file input stream. FileInputStream fis = openFileInput(FILE_NAME);
These methods support only those files in the current application folder; specifying path separators will cause an exception to be thrown.
If the file name you specify when creating a FileOutputStream does not exist, Android will create it for you. The default behavior for existing files is to overwrite them; to append an existing file, specify the mode as Context.MODE_APPEND.
By default, files created using the openFileOutput method are private to the calling application — a different application will be denied access. The standard way to share a file between applications is to use a Content Provider. Alternatively, you can specify either Context.MODE_WORLD_READABLE or Context.MODE_WORLD_WRITEABLE when creating the output file, to make it available in other applications, as shown in the following snippet:
String OUTPUT_FILE = "publicCopy.txt";
FileOutputStream fos = openFileOutput(OUTPUT_FILE, Context.MODE_WORLD_WRITEABLE);
Was this article helpful?
Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.