首先要申请权限,一个是在AndroidManifest.xml 中申请的存储权限
而后在activity 中动态申请
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); }
然后去查询当前Android设备所连接的设备
/** * 6.0获取外置sdcard和U盘路径,并区分 * author: sfy * @param mContext * @param keyword SD = "内部存储"; EXT = "SD卡"; USB = "U盘" * @return */ public String getStoragePath(Context mContext, String keyword) { String targetpath = ""; 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"); Object result = getVolumeList.invoke(mStorageManager); final int length = Array.getLength(result); Method getUserLabel = storageVolumeClazz.getMethod("getUserLabel"); for (int i = 0; i < length; i++) { Object storageVolumeElement = Array.get(result, i); String userLabel = (String) getUserLabel.invoke(storageVolumeElement); String path = (String) getPath.invoke(storageVolumeElement); if (userLabel.contains(keyword)) { targetpath = path; refreshFileList(targetpath); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return targetpath; }
然后你就可以通过这个地址去拿你想要的文件(递归)
public Map refreshFileList(String strPath) { String filename;//文件名 String suf;//文件后缀 File dir = new File(strPath);//文件夹dir File[] files = dir.listFiles();//文件夹下的所有文件或文件夹 if (files == null) return null; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { refreshFileList(files[i].getAbsolutePath());//递归文件夹!!! } else { filename = files[i].getName(); int j = filename.lastIndexOf("."); suf = filename.substring(j + 1);//得到文件后缀
// 这里根据你想要文件的后缀去查询,也可以根据文件名称去查询 } } return fileMap; }目前来说,这个 方法使用时并不卡顿,但是数据量多了之后可能就要去做优化了,欢迎提供各种优化建议