Wednesday, 13 February 2013

Saving files in Android.

Saving Files

Choose Internal or External Storage


All Android devices have two file storage areas: "internal" and "external" storage.  You can choose your need based on the differences between them at find in below comparison:

Internal storage
External storage
·         It's always available.
·         Files saved here are accessible by only your app by default.
·         When the user uninstalls your app, the system removes all your app's files from internal storage.
·         Internal storage is best when you want to be sure that neither the user nor other apps can access your files.

·         It's not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.
·         It's world-readable, so files saved here may be read outside of your control.
·         When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from getExternalFilesDir()

Writing in internal storage didn’t need any permission however to write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:
<manifest ...>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

</manifest>

Note: 

  • now we can read without taking a permission but in next release it will be needed to add this permission “READ_EXTERNAL_STORAGE” permission.
  • However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.

 Save a File on Internal Storage


When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
Returns a File representing an internal directory for your app.
Returns a File representing an internal directory for your app's temporary cache files.

Note: Be sure to delete each file once it is no longer needed. If the system begins running low on storage, it may delete your cache files without warning. 
To create a new file

File file = new File(context.getFilesDir(), filename);

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here's how to write some text to a file:

String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(string.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

Or, if you need to cache some files, you should instead use createTempFile().
For example, the following method extracts the file name from a URL and creates a file with that name in your app's internal cache directory:

public File getTempFile(Context context, String url)
{
    File file;
    try {
        String fileName = Uri.parse(url).getLastPathSegment();
        file = File.createTempFile(fileName, null, context.getCacheDir());
    catch (IOException e) {
        // Error while creating file
    }
    return file;
}

Save a File on External Storage


Check if the external memory is available using getExternalStorageState()methodIf the returned state is equal to MEDIA_MOUNTED, then you can read and write your files

Example:
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable()
{   String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) 
    {
        return true;
    }
    return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() 
{
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

Files type :
·         Public files
Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.
          For example, photos captured by your app.
·         Private files
Files that rightfully belong to your app and should be deleted when the user uninstalls your app, those files aren’t  realistically providing value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app's external private directory.

For example, additional resources downloaded by your app or temporary media files.

If you want to save public files on the external storage, use

the  getExternalStoragePublicDirectory() method to get a File representing the appropriate directory on the external storage.

The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES. For example:

public File getAlbumStorageDir(String albumName)
{
    // Get the directory for the user's public pictures directory.
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), albumName);


    if (!file.mkdirs()) 
   {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}

To save files that is private to your app,Call getExternalFilesDir() and pass it a name indicating the type of directory.

Each directory created this way is added to a parent directory that encapsulates all your app's external storage files,

The system deletes when the user uninstalls your app.
For example, here's a method you can use to create a directory for an individual photo album:
public File getAlbumStorageDir(Context context, String albumName) {


    // Get the directory for the app's private pictures directory.
    File file = new File(context.getExternalFilesDir(
            Environment.DIRECTORY_PICTURES), albumName);
    if (!file.mkdirs()) 
    {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}
If none of the pre-defined sub-directory names suit your files, you can instead call getExternalFilesDir()and pass null. This returns the root directory for your app's private directory on the external storage.
·         getExternalFilesDir() creates a directory inside a directory that is deleted when the user uninstalls your app.
·         usegetExternalStoragePublicDirectory()If the files you're saving should remain available after the user uninstalls your app


it's important that you use directory names provided by API constants like DIRECTORY_PICTURES. These directory names ensure that the files are treated properly by the system.
For instance, files saved in DIRECTORY_RINGTONES are categorized by the system media scanner as ringtones instead of music.

Query Free Space


you can find out whether sufficient space is available without causing an IOException by calling getFreeSpace() or getTotalSpace().

the system does not guarantee that you can write as many bytes as are indicated by getFreeSpace(). If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it's probably safe to proceed. Otherwise, you probably shouldn't write to storage.

Delete a File


You should always delete files that you no longer need.
Code:
myFile.delete();
If the file is saved on internal storage, you can also ask the Context to locate and delete a file by callingdeleteFile():
myContext.deleteFile(fileName);

Note: you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.

Source :http://developer.android.com/training/basics/data-storage/files.html


No comments:

Post a Comment