Android开发获取多个存储空间的路径(内置SD卡以及外置SD卡)

时间:2022-08-30 22:33:10

Android开发中经常会遇到多存储空间的问题,包括内置存储路径以及外置SD卡,而且有的时候会有多张外置SD卡,此时就需要获取不同的SD卡路径,然后根据需要来写入或者读出文件。

此处给出常用的SD卡工具类,用于获取内外部存储路径。

/**
* Created by Travis1022 on 2017/8/8.
*/ public class SdCardUtil {
/**
* 获取内置SD卡路径
*
* @return
*/
public static String getInnerSDCardPath() {
return Environment.getExternalStorageDirectory().getPath();
} /**
* 获取存储路径
* @return 所有可用于存储的不同的卡的位置,用一个List来保存
*/
public static List<String> getExtSDCardPathList() {
List<String> paths = new ArrayList<String>();
String extFileStatus = Environment.getExternalStorageState();
File extFile = Environment.getExternalStorageDirectory();
//首先判断一下外置SD卡的状态,处于挂载状态才能获取的到
if (extFileStatus.equals(Environment.MEDIA_MOUNTED) && extFile.exists() && extFile.isDirectory() && extFile.canWrite()) {
//外置SD卡的路径
paths.add(extFile.getAbsolutePath());
}
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("mount");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
int mountPathIndex = 1;
while ((line = br.readLine()) != null) {
// format of sdcard file system: vfat/fuse
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 (mountPathIndex >= length) {
continue;
}
String mountPath = parts[mountPathIndex];
if (!mountPath.contains("/") || mountPath.contains("data")
|| mountPath.contains("Data")) {
continue;
}
File mountRoot = new File(mountPath);
if (!mountRoot.exists() || !mountRoot.isDirectory()
|| !mountRoot.canWrite()) {
continue;
}
boolean equalsToPrimarySD = mountPath.equals(extFile
.getAbsolutePath());
if (equalsToPrimarySD) {
continue;
}
//扩展存储卡即TF卡或者SD卡路径
paths.add(mountPath);
}
} catch (IOException e) {
e.printStackTrace();
}
return paths;
} }
getInnerSDCardPath()即为直接获取内部存储空间的路径,而对应的getExtSDCardPathList()用于获取所有的存储路径,也包含内部存储路径。

效果如下:

Android开发获取多个存储空间的路径(内置SD卡以及外置SD卡)

对应的日志如下:

E/Logger: [ (SdCardUtil.java:98)#main ] 路径:/storage/emulated/0
                             E/Logger: [ (SdCardUtil.java:98)#main ] 路径:/storage/uicc0
                             E/Logger: [ (SdCardUtil.java:98)#main ] 路径:/storage/sdcard1