SAVING AND LOADING FILES

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.

Saving and loading files
String FILE_NAME = "tempfile.tmp";
// 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.

INCLUDING STATIC FILES AS RESOURCES
If your application requires external file resources, you can include them in your distribution package by placing them in the res/raw folder of your project hierarchy.

To access these read-only file resources, call the openRawResource method from your application’s Resource object to receive an InputStream based on the specified file. Pass in the file name (without extension) as the variable name from the R.raw class, as shown in the following skeleton code:

Resources myResources = getResources();
InputStream myFile = myResources.openRawResource(R.raw.myfilename);

Adding raw files to your resources hierarchy is an excellent alternative for large, preexisting data sources (such as dictionaries) for which it’s not desirable (or even possible) to convert them into Android databases.

Android’s resource mechanism lets you specify alternative resource files for different languages, locations, and hardware configurations. You could, for example, create an application that loads a different dictionary resource based on the user’s language settings.

FILE MANAGEMENT TOOLS
Android supplies some basic file management tools to help you deal with the file system. Many of these utilities are located within the standard java.io.File package.

➤ deleteFile Enables you to remove files created by the current application.
➤ fileList Returns a string array that includes all the files created by the current application.

These methods are particularly useful for cleaning up temporary files left behind if your application
crashes or is killed unexpectedly.

No comments:

Post a Comment