Search code examples
androidandroid-4.4-kitkatsd-card

Find real sd card path and write a file


My device is htc one dual sim and for some reason Environment.getExternalStorageDirectory() is my memory of the phone, it's not removable sd card. I tried to find the real sd card path using this:

   public static HashSet<String> getExternalMounts() {
        final HashSet<String> out = new HashSet<String>();
        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;
    }

And i got /mnt/media_rw/ext_sd

I tried to write files to /mnt/media_rw/ext_sd/downloads but the file didn't appear to be created.

  File file = new File("/mnt/media_rw/ext_sd/downloads", "test.txt");
        FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            writer.write("sdfsdfsfd");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


02-11 23:12:35.236    9110-9110/www.jenyakirmiza.com.testsdcard W/System.err﹕ java.io.FileNotFoundException: /mnt/media_rw/ext_sd/downloads/test.txt: open failed: EACCES (Permission denied)

I heard smth about restriction starting from 4.4 so now we can't write files to removable sd card. But they said you can write filed to /sdcardpath/Android/data/your.package.name

ps. of course i added write_external permisssion to manifest.


Solution

  • You can find all external storages with Context.getExternalMediaDirs and can check whether it is removable with Environment.isExternalStorageRemovable(File). Note that Downloads directory will most likely be only in the primary (emulated) external storage.