Android
项目需要使用SDCrad,用来记载程序的异常Log.但是在使用的时候,遇到了一个不算问题的问题.在使用
Environment.getExternalStorageDirectory().getAbsolutePath()
获取外置SDCard的时候,手动输出一条Log信息后.查看外置SDCard找不到写出的文件.却在手机内置的存储中看到生成的文件,这就让我觉得很奇怪了,我明明写的是在外置SDCard,为什么却生成在内置存储中.然后用获取到的SDCard的目录输出的是正常的SDCard的根目录 /mnt/sdcard/
然而在尝试过几次之后发现都是这个目录,但是写出的就是在内置SDCard中,果断百度之.但在百度找到的都是一些散乱的文章,尝试过几次之后发现都是不行.于是google之,终于在stackoverflow上找到了这么一段,大致问题跟我遇到的差不多
这是大神给的回复
翻译过来大意大概是在使用Environment.getExternalStorageDirectory().getAbsolutePath()获取SDCard的时候,获取到的是设备中所指定的"外置SDCard".这个外置可以是扩展的SDCard也可以是设备内部的存储空间.看到这里,终于明白了.于是与电子工程师沟通,查看了底层固件的SDCard挂载配置文件.发现在SDCard配置中. /mnt/sdcard一项中指向的是内置存储,而外置扩展的SDCard指向的是挂载路径是/mnt/sdcard0于是修改代码,吸收上次的教训,这次决定不能简单的使用getExternalStorageDirectory这么简单的获取,于是决定使用mount命令来获取.
mount是linux获取挂载点的命令,在这里由于篇幅的问题,就不在此赘述了.不明白的可以去百度,有很多写的很好的文章
下面贴上代码
public static List<String> getMountPath() {
List<String> paths = new ArrayList<>();
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
Runtime run = Runtime.getRuntime();
Process proc = run.exec("mount");
is = proc.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
if ((!line.contains("fat") && !line.contains("fuse") && !line.contains("storage"))
|| line.contains("secure")
|| line.contains("asec")
|| line.contains("firmware")
|| line.contains("shell")
|| line.contains("obb")
|| line.contains("legacy")
|| line.contains("data")) {
continue;
}
String[] parts = line.split(" ");
int length = parts.length;
if (1 >= length)
continue;
String mountPath = parts[1];
if (!mountPath.contains("/") || mountPath.contains("data") || mountPath.contains
("Data"))
continue;
File mountRoot = new File(parts[1]);
if (!mountRoot.exists() || !mountRoot.isDirectory() || !mountRoot.canWrite())
continue;
if (mountPath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()))
continue;
if (!Environment.isExternalStorageRemovable(mountRoot))
continue;
paths.add(mountPath);
LogUtils.e("--mountRootPath--->>", "" + mountPath);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) is.close();
if (isr != null) isr.close();
if (br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return paths;
}
这个方法我是封装在FileUtils中,返回值是所有的外部存储设备包括U盘等
本文解决了一个常见的Android开发问题:如何正确获取外置SDCard路径。作者通过对比内置存储与外置SDCard的区别,介绍了如何利用mount命令获取正确的路径。
4916

被折叠的 条评论
为什么被折叠?



