time

How-to read/write files in Android

Read from res directory

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 filename (without the extension) as the variable name from the R.raw class, as shown in the following code

Resources r = getResources();
InputStream file = r.openRawResource(R.raw.filename);

Read from assets directory

Android offers one more directory where you can keep files which also will be included in package. This directory called /assets. There are some difference from res directory.

With resources, there's built-in support for providing alternatives for different languages, OS versions, screen orientations, etc., as described here. None of that is available with assets. Also, many parts of the API support the use of resource identifiers. Finally, the names of the resources are turned into constant field names that are checked at compile time, so there's less of an opportunity for mismatches between the code and the resources themselves. None of that applies to assets.source
Context context = getApplicationContext();
InputStream is = context.getAssets().open(filename);
String text = "";

int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);

Read/Write to Internal Storage

This area of storage is sort of private to the application. It is always available to the application and gets purged when the app is uninstalled by the user.

Internal storage refers to the hard drive on device. Internal storage gives you the ability to prevent other applications from accessing the files you save and are tied directly to your app.

Files stored in /data/data/packagename/files/filename.txt. There are few modes for file access

  • MODE_PRIVATE - create a new file or overwrite one if it already exists with the same name
  • MODE_APPEND - create the file if it doesn’t exist and allow you to append to the file if it does exist
  • MODE_WORLD_READABLE - file is readable by any other application
  • MODE_WORLD_WRITEABLE - file is writeable by any other application

Write to file in internal storage

String FILE_NAME = "file.txt";
try {
    FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
    fos.write(someText.toString().getBytes());
    fos.close();
} catch (Exception e) {
    e.printStackTrace();
}

Read from file in internal storage

try {
    BufferedReader bReader = new BufferedReader(new InputStreamReader(openFileInput(FILE_NAME)));
    String line;
    StringBuffer text = new StringBuffer();                
    while ((line = bReader.readLine()) != null) {
        text.append(line + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
}

Read/Write to SDCard

External storage is typically either a removable storage media (i.e. SD Card) or an internal non-removable storage that is accessed in the same manner.

The most important thing to remember when storing files on external storage is that no security is enforced on files stored here. Any application can access, overwrite, or delete files stored on the external storage.

In order to write data to SDCard, the application need permission WRITE_EXTERNAL_STORAGE, which can be specified in the file AndroidManifest.xml.

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

Check external storage

private static boolean isExternalStorageReadOnly() {
    String extStorageState = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
        return true;
    }
    return false;
}

private static boolean isExternalStorageAvailable() {
    String extStorageState = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
        return true;
    }
    return false;
}

Write to SDCard

String FILE_NAME = "file.txt";
if (isExternalStorageAvailable() && isExternalStorageReadOnly()) {
    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(baseDir, FILE_NAME);
    FileWriter writer = null;
    try {
        writer = new FileWriter(file);
        writer.write(text.toString());
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }    
}

Read from SDCard

String FILE_NAME = "file.txt";
if (isExternalStorageAvailable() && isExternalStorageReadOnly()) {
    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(baseDir, FILE_NAME);

    String line = "";
    StringBuilder text = new StringBuilder();

    try {
        FileReader fReader = new FileReader(file);
        BufferedReader bReader = new BufferedReader(fReader);

        while( (line = bReader.readLine()) != null  ){
            text.append(line+"\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Read/Write to Cache

Should your application need to cache temporary files, Android offers both a managed internal cache, and (since Android API level 8) an unmanaged external cache. You can access them by calling the getCacheDir and getExternalCacheDir methods, respectively, from the current Context.

Files stored in either cache location will be erased when the application is uninstalled. Files stored in the internal cache will potentially be erased by the system when it is running low on available storage; files stored on the external cache will not be erased, as the system does not track available storage on external media.

Read from cache dir

String TMP_FILE_NAME = "tmp_file.txt";
File tmpFile;

File cacheDir = getBaseContext().getCacheDir();
tmpFile = new File(cacheDir.getPath() + "/" + TMP_FILE_NAME) ;

String line="";
StringBuilder text = new StringBuilder();

try {
    FileReader fReader = new FileReader(tmpFile);
    BufferedReader bReader = new BufferedReader(fReader);

    while( (line=bReader.readLine()) != null  ){
        text.append(line+"\n");
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}catch(IOException e){
    e.printStackTrace();
}

Write to cache dir

FileWriter writer = null;
try {
    writer = new FileWriter(tmpFile);
    writer.write(text.toString());
    writer.close();

    // path to file
    // tmpFile.getPath() 

} catch (IOException e) {
    e.printStackTrace();
}

Read/Write to publicly readable files

Android 2.2 (API level 8) includes a convenience method, Environment.getExternalStoragePublicDirectory, that can be used to find a path in which to store your application files. The returned location is where users will typically place and manage their own files of each type. Files that’ll remain on the storage even after the application is uninstalled by the user like media (photos, videos, etc.) or other downloaded files. This is particularly useful for applications that provide functionality that replaces or augments system applications, such as the camera, that store files in standard locations.

There are 2 methods that we can use to get the public external storage directory for placing files:

  • getExternalStorageDirectory() method returns the primary (top-level or root) external storage directory.
  • getExternalStoragePublicDirectorty method returns a top level public external storage directory for showing files of a particular type based on the argument passed. So basically the external storage has directories like Music, Podcasts, Pictures, etc. whose paths can be determined and returned via this function by passing the appropriate environment constants.

The getExternalStoragePublicDirectory method accepts a string parameter that determines which subdirectory you want to access using a series of Environment static constants:

  • DIRECTORY_DCIM - pictures and videos taken by the device
  • DIRECTORY_DOWNLOADS - files downloaded by the user
  • DIRECTORY_MOVIES — movies
  • DIRECTORY_MUSIC — audio fi les that represent music
  • DIRECTORY_PICTURES — pictures

Note that if the returned directory doesn’t exit, you must create it before writing fi les to the directory, as shown in the following snippet

String IMAGE_FILE_NAME = "image.png";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path, FILE_NAME);
try {
    path.mkdirs();
    // statements for file store
} catch (IOException e) {
    Log.d(TAG, "Error writing " + IMAGE_FILE_NAME, e);
}

Online video

Guys from Webucator make nice video about How to Read and Write Files in Android. Also you can try online course Android Training.

Useful links

comments powered by Disqus