找到真正的sd卡路径并写入文件

Find real sd card path and write a file

我的设备是 htc one dual sim 并且出于某种原因 Environment.getExternalStorageDirectory() 是我对 phone 的记忆,它不是可移动的 sd 卡。 我试图用这个找到真正的 sd 卡路径:

   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;
    }

然后我得到了 /mnt/media_rw/ext_sd

我尝试将文件写入 /mnt/media_rw/ext_sd/downloads 但是文件似乎没有创建。

  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)

我听说从 4.4 开始有限制,所以现在我们不能将文件写入可移动 sd 卡。但是他们说你可以写 filed to /sdcardpath/Android/data/your.package.name

ps。当然,我添加了 write_external 权限以显示。

您可以通过 Context.getExternalMediaDirs and can check whether it is removable with Environment.isExternalStorageRemovable(File) 查找所有外部存储。请注意,下载目录很可能仅位于主要(模拟)外部存储中。

尝试使用 Environment.getExternalStorageDirectory() 方法:

File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "test.txt");

你可以先用exists()方法评估你的文件是否真的存在:

  File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "test.txt");
    if(file.exists()){

      FileWriter writer = null;
        try {
            writer = new FileWriter(file);
            writer.write("sdfsdfsfd");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

获得此权限非常重要:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

在你的

里面
 AndroidManifest.xml