java 如何在Android上查找具有特定扩展名的所有文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7040197/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:25:33  来源:igfitidea点击:

How to find all files with certain extension on Android?

javaandroidfile-browser

提问by Vitor Rangel

I'm using a fileBrowser to find the files on the phone, but I wanted to show all files that my app can open to the user, and then the user chooses one. Like the Music Player, that show all songs on phone, on the sdcard and in the internal memory, not only the ones in the folder where the user is.

我正在使用 fileBrowser 在手机上查找文件,但我想显示我的应用程序可以向用户打开的所有文件,然后用户选择一个。就像音乐播放器一样,它会显示手机、SD 卡和内存中的所有歌曲,而不仅仅是用户所在文件夹中的歌曲。

采纳答案by bluefalcon

Use file name filters while listing out the files. The below sample lists out all mp3 files in a given rootdirectory (Note - The below code doesn't do it recursively for all folders under root) -

列出文件时使用文件名过滤器。下面的示例列出了给定root目录中的所有 mp3 文件(注意 - 下面的代码不会对 下的所有文件夹递归执行root) -

String files[] = root.list(audioFilter);

FilenameFilter audioFilter = new FilenameFilter() {
    File f;
    public boolean accept(File dir, String name) {
    if(name.endsWith(".mp3") || name.endsWith(".MP3")) {
            return true;
        }
        f = new File(dir.getAbsolutePath()+"/"+name);

        return f.isDirectory();
    }
};

回答by Vlad

I don't know what FileBrowser implementation you are using but a good one should accept a FileFilter. You can implement your own filter providing code for public abstract boolean accept (File pathname)

我不知道您使用的是什么 FileBrowser 实现,但一个好的实现应该接受FileFilter。您可以实现自己的过滤器提供代码public abstract boolean accept (File pathname)