Android 两种方获取U盘的挂载路径

发布时间 2023-11-29 17:33:07作者: xiaowang_lj


第一种

public String getUsbPath() {
        try {
            StorageManager sm = (StorageManager) MyApplication.getContext().getSystemService(STORAGE_SERVICE);
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths",null);
            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null);
            return paths.length <= 1 ? null : paths[1];

        } catch (Exception e) {
            Log.e(TAG, "---getUsbPath() failed"+e);
        }
        return null;
    }

第二种

   private String getUsbPath() {
        String filePath = "/proc/mounts";
        File file = new File(filePath);
        List<String> lineList = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GBK");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    if (line.contains("vfat")) {
                        lineList.add(line);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String path = null;
        if (lineList.size() > 0) {
            String editPath = lineList.get(lineList.size() - 1);
            int start = editPath.indexOf("/mnt");
            int end = editPath.indexOf(" vfat");
            path = editPath.substring(start, end);
        }
        return path;
    }