Skip to content

Instantly share code, notes, and snippets.

@Bencodes
Created December 11, 2012 07:20
Show Gist options
  • Save Bencodes/4256543 to your computer and use it in GitHub Desktop.
Save Bencodes/4256543 to your computer and use it in GitHub Desktop.
Easy way of getting File paths in Android
public final class StorageUtil {
public static enum Storage {
/**
* /data/data/com.my.package/data/files/
*/
INTERNAL,
/**
* (Varies on manufacturer)
* /mnt/sdcard/
* /sdcard/
* <p/>
* etc...
*/
EXTERNAL,
/**
* /data/data/com.my.package/data/cache/
*/
INTERNAL_CACHE,
/**
* (Varies on manufacturer)
* /mnt/sdcard/Android/data/com.my.package/cache/
* /sdcard/Android/data/com.my.package/cache/
* <p/>
* etc...
*/
EXTERNAL_CACHE;
}
/**
* A simple all-in-one method for getting File paths in Android.
* If you request EXTERNAL/EXTERNAL_CACHE and there is no mounted external
* storage, it will automatically default to internal.
*
* @param context Context so that it can request the appropriate File path.
* @param storage Enum value for the preferred location (External/Internal)
* @param subDirectory A sub directory path just in case you want to get a sub directory
* @return
*/
public static File getStorageDirectory (final Context context, final Storage storage, final String subDirectory) {
final File directory;
switch (storage) {
case EXTERNAL:
case EXTERNAL_CACHE: {
// Check If External Even Exists
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
directory = (storage == Storage.EXTERNAL)
? Environment.getExternalStorageDirectory()
: context.getExternalCacheDir();
break;
}
}
case INTERNAL: {
directory = context.getFilesDir();
break;
}
case INTERNAL_CACHE: {
directory = context.getCacheDir();
break;
}
default: {
return null;
}
}
return new File(directory, subDirectory);
}
public static File getStorageDirectory (final Context context, final Storage storage) {
return getStorageDirectory(context, storage, null);
}
}
@lldeepakll
Copy link

How to use this class in android project ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment