-
-
Save baleen37/d84ac4af3d08f2c94669a2687922aeb7 to your computer and use it in GitHub Desktop.
Easy way of getting File paths in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment