我正在尝试获取内部存储和外部存储(可移动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 /”进行硬编码,因为我不确定所有设备在路径中都有这个字符串,它可能在我的设备上运行但可能不在其他设备上。
从内部和外部存储(SD卡)获取绝对路径的任何其他方式?
getActivity().getExternalFilesDirs(null)[0].getAbsolutePath();
我使用上面的代码时的Logcat路径值。
/storage/emulated/0/Android/data/com.package./files
它总是返回一个太长的路径,我需要到达内部和外部存储器的根。
我想你不需要子串代码。你可以用它。以下是您所说的外部路径。
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());
}