如题,现在的很多应用都有自动扫描sdcard文件的功能,例如天天动听等音乐播放器导入音乐的时候、还有一些阅读应用导入本地文本也有扫描功能。最近做一个练习,写到这个功能,只是简单的实现了扫描,并没有考虑手机内存等因素。
这里以扫描图片为例,扫描其它类型的文件,只需要换后缀名。
具体实现方法如下:
private List> l = new ArrayList>();
private HashMap hm;
//常见的图片格式
private String[] img = new String[] { ".jpg", ".png", ".gif", ".bmp" };
private void checkFile(File file) {// 遍历文件,在这里是遍历sdcard
if (file.isDirectory()) {// 判断是否是文件夹
File[] files = file.listFiles();// 以该文件夹的子文件或文件夹生成一个数组
if (files != null) {// 如果文件夹不为空
for (int i = 0; i < files.length; i++) {
File f = files[i];
checkFile(f);// 递归调用
}
}
} else if (file.isFile()) {// 判断是否是文件
int dot = file.getName().lastIndexOf(".");
if (dot > -1 && dot < file.getName().length()) {
String extriName = file.getName().substring(dot,
file.getName().length());// 得到文件的扩展名
if (extriName.equals(img[0]) || extriName.equals(img[1])
|| extriName.equals(img[2]) || extriName.equals(img[3])) {// 判断是否是图片文件
hm = new HashMap();
hm.put("name", file.getName());
hm.put("path", file.getPath());// 如果是图片,则得到文件名和路径,装入集合中
l.add(hm);
}
}
}
}
我把路径保存起来,以后方便建立Bitmap对象(BitmapFactory.decodeFile(path)方法)。
之前在网上看到,android系统启动的时候会自动扫描手机中的媒体文件,并把扫描的信息保存在某个文件中,而我们可以读取到这个文件的信息,具体请参看MediaStore类,通过这个类可以实现,这里就不做叙述。
转载于:https://blog.51cto.com/52xiaohui/1181031