如何使用getExternalFilesDirs获取内部和外部(SD卡)路径?

时间:2019-03-10 03:10:01

标签: java android android-sdcard android-external-storage android-storage

我正在尝试获取内部存储外部存储(可移动SD卡)的路径。

我尝试过的是这个

内部路径

path = getActivity().getExternalFilesDirs(null)[0].getAbsolutePath();

外部路径

path = getActivity().getExternalFilesDirs(null)[1].getAbsolutePath();

Logcat

内部路径返回:

/storage/emulated/0/Android/data/com.package./files

并在 SubString 的帮助下,我设法转到了该路径

/storage/emulated/0/

子字符串代码

int index = path.lastIndexOf("/Android/data/");
if (index > 0){
path =  path.substring(0, index);
Log.d(TAG, "value path0: " + path);
}

对于外部路径,我对 SubString 做了同样的事情,并且返回

/storage/3EC7-2342

现在,我不确定是否可以对字符串“ / Android / data /” 进行硬编码,因为我不确定所有设备在其路径中是否都具有此字符串,并且可能可以在我的设备上工作,但可能无法在其他设备上工作。

是否还可以通过其他方式从内部外部存储(sdcard)获取绝对路径

getActivity().getExternalFilesDirs(null)[0].getAbsolutePath();
当我使用上面的代码时,

Logcat路径值。

/storage/emulated/0/Android/data/com.package./files

它总是返回太长的路径,我需要到达内部和外部存储器的根。

2 个答案:

答案 0 :(得分:0)

我想您不需要子字符串代码。您可以使用它。以下是您声明的外部路径。

File file1 =  getApplicationContext().getExternalFilesDirs(null)[1];
    while(!file1.getParentFile().getAbsolutePath().equals("/storage")) {

        file1 = file1.getParentFile();
        System.out.println(file1.getAbsolutePath());
    }

您可以类似地将其用于内部路径。

再三考虑,如果将来的“存储”也发生变化,那么下面的代码应该起作用。

String path = null;
    File file1 =  getApplicationContext().getExternalFilesDirs(null)[1];
    while(!file1.getParentFile().getAbsolutePath().equals("/")) {

        file1 = file1.getParentFile();
        path = file1.getAbsolutePath();
        //System.out.println(file1.getAbsolutePath());
    }
    file1 =  getApplicationContext().getExternalFilesDirs(null)[1];
    while(!file1.getParentFile().getAbsolutePath().equals(path)) {

        file1 = file1.getParentFile();
        System.out.println(file1.getAbsolutePath());
    }

答案 1 :(得分:0)

根据 getExternalFilesDirs 的文档,我认为可以假设根目录后面总会有一个“Android”文件夹。

            //List of the storages
            List<File> storage = new ArrayList<>();
            File[] files = ContextCompat.getExternalFilesDirs(this, null);
            for (File file : files) {

                File parent = file.getParentFile();
                while (parent != null && !parent.getPath().endsWith(File.separator + "Android")) {

                    parent = parent.getParentFile();
                }
                if (parent!=null) // add to the list
                    storage.add(parent.getParentFile());
            }
相关问题