java 在android中扫描文件夹以获取文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5279404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scan a file folder in android for file paths
提问by Peter
So i have a folder at "mnt/sdcard/folder" and its filled with image files. I want to be able to scan the folder and for each of the files that is in the folder put each file path in an arraylist. Is there an easy way to do this?
所以我在“mnt/sdcard/folder”有一个文件夹,里面装满了图像文件。我希望能够扫描文件夹,并且对于文件夹中的每个文件,将每个文件路径放在一个数组列表中。是否有捷径可寻?
回答by David Lantos
You could use
你可以用
List<String> paths = new ArrayList<String>();
File directory = new File("/mnt/sdcard/folder");
File[] files = directory.listFiles();
for (int i = 0; i < files.length; ++i) {
paths.add(files[i].getAbsolutePath());
}
See listFiles()
variants in File
(one empty, one FileFilter
and one FilenameFilter
).
请参阅(one empty, one and one ) 中的listFiles()
变体。File
FileFilter
FilenameFilter
回答by Matthew Willis
Yes, you can use the java.io.File
API with FileFilter.
是的,您可以将java.io.File
API 与FileFilter 一起使用。
File dir = new File(path);
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File file) {
return file.getAbsolutePath().matches(".*\.png");
}
};
File[] images = dir.listFiles(filter);
I was quite surprised when I saw this technique, as it's quite easy to use and makes for readable code.
当我看到这种技术时,我感到非常惊讶,因为它非常易于使用并且可以编写可读的代码。