Find location of a removable SD card

前端 未结 22 2593
南方客
南方客 2020-11-21 11:32

Is there an universal way to find the location of an external SD card?

Please, do not be confused with External Storage.

Environment.getExternalStorage

22条回答
  •  [愿得一人]
    2020-11-21 11:57

    Its work for all external devices, But make sure only get external device folder name and then you need to get file from given location using File class.

    public static List getExternalMounts() {
            final List out = new ArrayList<>();
            String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
            String s = "";
            try {
                final Process process = new ProcessBuilder().command("mount")
                        .redirectErrorStream(true).start();
                process.waitFor();
                final InputStream is = process.getInputStream();
                final byte[] buffer = new byte[1024];
                while (is.read(buffer) != -1) {
                    s = s + new String(buffer);
                }
                is.close();
            } catch (final Exception e) {
                e.printStackTrace();
            }
    
            // parse output
            final String[] lines = s.split("\n");
            for (String line : lines) {
                if (!line.toLowerCase(Locale.US).contains("asec")) {
                    if (line.matches(reg)) {
                        String[] parts = line.split(" ");
                        for (String part : parts) {
                            if (part.startsWith("/"))
                                if (!part.toLowerCase(Locale.US).contains("vold"))
                                    out.add(part);
                        }
                    }
                }
            }
            return out;
        }
    

    Calling:

    List list=getExternalMounts();
            if(list.size()>0)
            {
                String[] arr=list.get(0).split("/");
                int size=0;
                if(arr!=null && arr.length>0) {
                    size= arr.length - 1;
                }
                File parentDir=new File("/storage/"+arr[size]);
                if(parentDir.listFiles()!=null){
                    File parent[] = parentDir.listFiles();
    
                    for (int i = 0; i < parent.length; i++) {
    
                        // get file path as parent[i].getAbsolutePath());
    
                    }
                }
            }
    

    Getting access to external storage

    In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions. For example:

    
        
        ...
    
    

提交回复
热议问题