今天项目一个问题涉及了手机文件存储,特此记录一下
一般手机存储分为 内部存储 和外部存储
内部存储路径获取方式有两种
String url = Environment.getExternalStorageDirectory() + File.separator + "ceshi" + File.separator + "08ea24f490532d2e4d7c69e8b69a8f01.m3u8.sqlite"; Log.e("TAG", "onCreate:------------ " + url); final File externalStorageDirectory = Environment.getExternalStorageDirectory(); final File ceshi = new File(externalStorageDirectory, "ceshi"); Log.e("TAG", "onCreate:++++++++++++ " + ceshi + File.separator + "08ea24f490532d2e4d7c69e8b69a8f01.m3u8.sqlite"); File directory_pictures = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); Log.e("TAG", "onCreate:------------ " + directory_pictures + File.separator + "08ea24f490532d2e4d7c69e8b69a8f01.m3u8.sqlite");
一二都是同一种的不同写法
第二种方法是一个更加方便的访问Android给我们提供好的一些公共目录的方法,第一种方式更加灵活,可以自己指定目录
外部存储又分为SD卡和扩展卡内存
扩展内存就是我们插入的外置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; }
测试路径
Log.e("TAG", "外置SD卡路径 = " + getExtendedMemoryPath(this)); Log.e("TAG", "内置SD卡路径 = " + Environment.getExternalStorageDirectory().getAbsolutePath()); Log.e("TAG", "手机内存根目录路径 = " + Environment.getDataDirectory().getParentFile().getAbsolutePath());