Wednesday 17 August 2016

File Handling Part-1

android file part1

Android uses a file system that's similar to disk-based file systems on other platforms. 
A File object is suited to reading or writing large amounts of data in start-to-finish order without skipping around.
The lesson assumes that you are familiar with the basics of the Linux file system and the standard file input/output APIs in java.io.
All Android devices have two file storage areas: "internal (Phone memory)" and "external ( sdard, usb )" storage.
 The following lists summarize the facts about each storage space.
Internal 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.
External storage:
·         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().
External storage is the best place for files that don't require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.

Saving data to external storage
Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage.
Caution: External storage can become unavailable if the user mounts the external storage on a computer or removes the media, and there's no security enforced upon files you save to the external storage. All applications can read and write files placed on the external storage and the user can remove them.

Getting access to external storage
In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions. For example:
<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>
If you need to both read and write files, then you need to request only the WRITE_EXTERNAL_STORAGE permission, because it implicitly requires read access as well.
Note: Beginning with Android 4.4, these permissions are not required if you're reading or writing only files that are private to your app. For more information,
<manifest ...>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    ...

</manifest>
However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.
You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.

Save a File on External Storage


Because the external storage may be unavailable—such as when the user has mounted the storage to a PC or has removed the SD card that provides the external storage—you should always verify that the volume is available before accessing it. You can query the external storage state by callinggetExternalStorageState(). If the returned state is equal to MEDIA_MOUNTED, then you can read and write your files. For example, the following methods are useful to determine the storage availability:
/* 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;

}
Although the external storage is modifiable by the user and other apps, there are two categories of files you might save here:
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 or other downloaded files.
Private files
Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don't provide 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.
Directory list DIRECTORY_ALARMS,DIRECTORY_DCIM,DIRECTORY_DOCUMENTS,DIRECTORY_DOWNLOADS,DIRECTORY_MOVIES,DIRECTORY_MUSIC,DIRECTORY_NOTIFICATIONS,DIRECTORY_PICTURES,DIRECTORY_PODCASTS,DIRECTORY_RINGTONES
 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;

}
If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing it a name indicating the type of directory you'd like. Each directory created this way is added to a parent directory that encapsulates all your app's external storage files, which 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.

-----------------

Using the Internal Storage


You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.
To create and write a private file to the internal storage:
1.     Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.
2.     Write to the file with write().
3.     Close the stream with close().
For example:
String FILENAME = "hello_file";

String string = "hello world!";



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

fos.write(string.getBytes());

fos.close();
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. Other modes available are: MODE_APPEND,MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
To read a file from internal storage:
1.     Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
2.     Read bytes from the file with read().
3.     Then close the stream with close().
Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it withopenRawResource(), passing the R.raw.<filename> resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).



22



No comments:

Post a Comment