赞
踩
AndroidManifest.xml之前已经加入了以下权限
- <!-- 允许应用程序读取设备外部存储 -->
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- <!-- 允许应用程序写入设备外部存储 -->
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后在写入文件到U盘的过程中,出现如下错误
java.io.FileNotFoundException: /storage/001A-DE3C/x.png (Permission denied)
java.io.FileNotFoundException: /storage/001A-DE3C/Detection/report/x.png (No such file or directory)
解决方法就是还需要添加下面的权限才可以
- <!-- 允许应用程序向外部存储设备写入媒体文件,用于解决无法写入文件到U盘的问题 -->
- <uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
最后分享一个获取设备上的USB路径列表的方法
- /**
- * 获取挂载在设备上的USB路径列表
- *
- * @param context 上下文对象
- * @return 挂载在设备上的USB路径列表
- */
- public static List < String > getUsbPathList(Context context) {
- List<String> usbPathList = new ArrayList<>();
- StorageManager storageManager =(StorageManager) context . getSystemService (Context.STORAGE_SERVICE);
- try {
- Method methodVolumeList = StorageManager .class.getMethod("getVolumeList");
- methodVolumeList.setAccessible(true);
- Object[] volumeList =(Object[]) methodVolumeList . invoke (storageManager);
- if (null == volumeList) {
- return null;
- }
-
- for (Object o: volumeList) {
- String path =(String) o . getClass ().getMethod("getPath").invoke(o);
- boolean isRemovable =(boolean) o . getClass ().getMethod("isRemovable").invoke(o);
- String state =(String) o . getClass ().getMethod("getState").invoke(o);
- if (isRemovable && "mounted".equalsIgnoreCase(state) && path.contains("storage")) {
- usbPathList.add(getCorrectPath(path));
- }
- }
- } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
- e.getLocalizedMessage();
- }
- return usbPathList;
- }
-
- /**
- * 根据从{@link getUsbPathList(Context)}获取到的路径来获取USB真正的路径
- *
- * @param path 从{@link getUsbPathList(Context)}获取到的路径
- * @return USB真正的路径
- */
- private static String getCorrectPath(String path) {
- if (TextUtils.isEmpty(path)) {
- return path;
- }
-
- int lastSeparator = path . lastIndexOf (File.separator);
- String endString = path . substring (lastSeparator + 1);
- if (TextUtils.isEmpty(endString)) {
- return path;
- }
-
- String usbDisk = "USB_DISK";
- String anotherUsbDisk = "usb_disk";
- if (endString.contains(usbDisk) || endString.contains(anotherUsbDisk)) {
- File file = new File(path);
- if (!file.exists()) {
- return path;
- }
-
- File[] files = file . listFiles ();
- if (null == files || 0 == files.length) {
- return path;
- }
-
- for (File f: files) {
- // 如果有多个路径,就获取第一个存在的路径.
- if (f.isDirectory()) {
- return f.getAbsolutePath();
- }
- }
- }
- return path;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。