ska*_*esh 1 media android android-image android-file
我试图在Android设备上找到包含图像(内部和外部存储)的所有目录.
基本上,我尝试获取本机库应用程序中列出的所有目录
例如:
如何实现这一目标?我认为它与MediaStorage.Images.Media等有关,但文档在那里并不是很有帮助,很多谷歌搜索也没有帮助.
您可以使用此代码在存储中查找图片文件夹 -
private ArrayList<File> fileList = new ArrayList<File>();
...
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].getName().endsWith(".png")
|| listFile[i].getName().endsWith(".jpg")
|| listFile[i].getName().endsWith(".jpeg")
|| listFile[i].getName().endsWith(".gif"))
{
String temp = file.getPath().substring(0, file.getPath().lastIndexOf('/'));
fileList.add(temp);
}
}
}
return fileList;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样打电话ArrayList-
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
getFile(root);
for (int i = 0; i < fileList.size(); i++) {
String stringFile = fileList.get(i).getName();
Do whatever you want to do with each filename here...
}
Run Code Online (Sandbox Code Playgroud)
感谢@BlazingFire,他没有完全回答我的问题,但是提供了一些我可以使用的代码,现在我得到了想要的结果:
public ArrayList<String> getFile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (File file : listFile) {
if (file.isDirectory()) {
getFile(file);
}
else {
if (file.getName().endsWith(".png")
|| file.getName().endsWith(".jpg")
|| file.getName().endsWith(".jpeg")
|| file.getName().endsWith(".gif")
|| file.getName().endsWith(".bmp")
|| file.getName().endsWith(".webp"))
{
String temp = file.getPath().substring(0, file.getPath().lastIndexOf('/'));
if (!fileList.contains(temp))
fileList.add(temp);
}
}
}
}
return fileList;
}
Run Code Online (Sandbox Code Playgroud)
仅添加图像的父目录,并且仅当它们尚未添加时才添加。我还包括.bmp和.webp作为有效的图像文件扩展名