Thursday, February 7, 2013

Android beginner tutorial: Part 75 - Internal Storage

In this tutorial we'll learn aboutusing the internal storage of an Android device.

It is possible to save files directly on your device's internal or external storage (for example, a memory card). When you save to your internal storage, other applications by default are unable to access these files - they are private to your application. When the user uninstalls your application, the files are also removed.

Reading and writing in Android is quite simple, somewhat similar to how its done in AS3 in Adobe AIR.

To read a file, you need to open it using openFileInput() method and apply the returned value to a FileInputStream instance. It is then used on a InputStreamReader object, which is then used by a BufferedReader object.

We can then read the file line by line and display the contents of the whole file:

FileInputStream in = openFileInput("file.txt");
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {

Writing files is done similarly. Instead of inputting data though, we output it. It actually takes less lines to write or update a file than read it:

String filename = "myfile";
String string = "Hello world!";

FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);

The MODE_PRIVATE keyword will make sure that the file is created or replaced if it already exists and be available only to your application. There are other modes like MODE_APPEND, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE.

If you want to save cache files, you can use the getCacheDir() function to open a File object that is the directory in your internal storage that you can use to store temporary cache files in. When the device is low on internal storage space, the Android system might delete your caches to gain some space. Even though Android takes the garbage out, you should maintain those files yourself and keep their size reasonable.

There are a few other useful methods that you can use when working with files in internal storage. Such methods are getFilesDir(), which shows the absolute path to the directory where your internal files are stored, getDir(), that creates or opens an existing directory in your internal space, deleteFile(), that deletes an internal file, and fileList(), that returns an array of files in the internal storage that your application saved.

That's all for today.

Thanks for reading!

No comments:

Post a Comment