现在市面上的手机大多有内置sd卡,而用户有的会加个外置sd卡,有的则只使用内置的sd卡。那么我们如果要获取sd卡(内置或外置)的数据,该怎么做?
直接贴代码(代码是从网上的找的,自己修改了一下)
/**
* 遍历 "system/etc/vold.fstab” 文件,获取全部的Android的挂载点信息
*
* @return
*/
private static ArrayList<String> getDevMountList() {
String[] toSearch = readSDFile("/etc/vold.fstab").split( " ");
ArrayList<String> out = new ArrayList<String>();
for (int i = 0; i < toSearch.length; i++) {
if (toSearch[i].contains("dev_mount" )) {
if (new File(toSearch[i + 2]).exists()) {
out.add(toSearch[i + 2]);
}
}
}
return out;
}
/**
* 获取扩展SD卡存储目录
*
* 如果有外接的SD卡,并且已挂载,则返回这个外置SD卡目录
* 否则:返回内置SD卡目录
*
* @return
*/
public static String getExternalSdCardPath() {
if (isMounted()) {
File sdCardFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
return sdCardFile.getAbsolutePath();
}
String path = null;
File sdCardFile = null;
ArrayList<String> devMountList = getDevMountList();
for (String devMount : devMountList) {
File file = new File(devMount);
if (file.isDirectory() && file.canWrite()) {
path = file.getAbsolutePath();
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss" ).format(new Dat e());
File testWritable = new File(path, "test_" + timeStamp);
if (testWritable.mkdirs()) {
testWritable.delete();
} else {
path = null;
}
}
}
if (path != null) {
sdCardFile = new File(path);
return sdCardFile.getAbsolutePath();
}
return null ;
}
/**
*
* 读取SD卡中文本文件
*
*
*
* @param fileName
*
* @return
*/
public static String readSDFile(String fileName) {
StringBuffer sb = new StringBuffer();
File file = new File(fileName);
try {
FileInputStream fis = new FileInputStream(file);
int c;
while ((c = fis.read()) != -1) {
sb.append(( char) c);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static boolean isMounted() {
if( Environment.getExternalStorageState().equals( "mounted"))
return true ;
else
return false ;
}