这里的内部存储对应的就是手机QQ的手机内存,路径为
Environment.getDataDirectory().getParentFile()
就是根目录,这个目录下还有一些私密的数据,比如:databases(数据库)、shared_prefs(SharedPreferences)等
注意:没有root的手机不能打开该文件夹的
2、外部存储
外部存储又分为SD卡和扩展卡内存
(1)SD卡
获取路径方式是
Environment.getExternalStorageDirectory()
/storage/sdcard0
Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS)
/storage/sdcard0/Download
Environment.getExternalStoragePublicDirectory(DIRECTORY_MOVIES)
/storage/sdcard0/Movies
Environment.getExternalStoragePublicDirectory(DIRECTORY_MUSIC)
/storage/sdcard0/Music
Environment.getExternalStoragePublicDirectory(DIRECTORY_NOTIFICATIONS)
/storage/sdcard0/Notifications
Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES)
/storage/sdcard0/Pictures
Environment.getExternalStoragePublicDirectory(DIRECTORY_PODCASTS)
/storage/sdcard0/Podcasts
Environment.getExternalStoragePublicDirectory(DIRECTORY_RINGTONES)
/storage/sdcard0/Ringtones
上面的九个方法对应的就是SD卡的九大公有目录,Google官方建议我们数据应该存储在私有目录下,不建议存储在公有目录下或其他地方
那什么是私有目录呢?
就是在外部存储的App的包名下,如:
/storage/emulated/0/Android/data/cwj.test(包名)/files/test
一般情况下有包名的路径我们都是调用Context中的方法来获得,没有包名的路径,我们直接调用Environment中的方法获得。
(2)扩展卡内存
扩展内存就是我们插入的外置SD卡,获取扩展内存的路径有点难度,不过Google很牛逼,哈哈,代码如下:
private static String getExtendedMemoryPath(Context mContext) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (removable) {
return path;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
该方法主要是通过反射的方式使用在sdk中被 隐藏 的类 StroageVolume 中的方法getVolumeList(),获取外部存储的路径。
路径测试:
Log.e("cwj", "外置SD卡路径 = " + getStoragePath(this));
Log.e("cwj", "内置SD卡路径 = " + Environment.getExternalStorageDirectory().getAbsolutePath());
Log.e("cwj", "手机内存根目录路径 = " + Environment.getDataDirectory().getParentFile().getAbsolutePath());