Skip to content Skip to sidebar Skip to footer

Storing .txt Files On Android

So I made the grave error of storing a bunch of .txt files in the Assets folder on Android only to discover that it is read-only and I need to be able to write to some of them, del

Solution 1:

Here is a sample code i use for getting the storage directory:

/**
 * Check if external storage is built-in or removable.
 *
 * @return True if external storage is removable (like an SD card), false
 *         otherwise.
 */
@TargetApi(9)
public static boolean isExternalStorageRemovable() {
    if (hasGingerbread()) {
        return Environment.isExternalStorageRemovable();
    }
    return true;
}

/**
 * Get the external app cache directory.
 *
 * @param context The context to use
 * @return The external cache dir
 */
@TargetApi(8)
public static File getExternalCacheDir(Context context) {
    if (hasFroyo()) {
        return context.getExternalCacheDir();
    }

    // Before Froyo we need to construct the external cache dir ourselves
    final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
    return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}



/**
 * Get a usable cache directory (external if available, internal otherwise).
 *
 * @param context The context to use
 * @param uniqueName A unique directory name to append to the cache dir
 * @return The cache dir
 */
public static File getDiskCacheDir(Context context, String uniqueName) {
    // Check if media is mounted or storage is built-in, if so, try and use external cache dir
    // otherwise use internal cache dir
    final String cachePath =
            Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                    !isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
                            context.getCacheDir().getPath();

    return new File(cachePath + File.separator + uniqueName);
}

And you got yourself a path to place your files....

And now to place them upon install, you should copy them on first run from your assets to that folder, or create them and populate them depending on your needs....and no there is no other way to have files shipped with your app, they can come in assets, you can create them from your app, or download them from some server.

Edit1: the folder will be in Android/data/your_package_name/cache+anything you want...

and the two functions used for gingerbread and froyo:

 public static boolean hasFroyo() {
    // Can use static final constants like FROYO, declared in later versions
    // of the OS since they are inlined at compile time. This is guaranteed behavior.
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}

public static boolean hasGingerbread() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}

Post a Comment for "Storing .txt Files On Android"