JAVA ANDROID - 获取文件夹的列表文件

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

JAVA ANDROID - get list files of a folder

javaandroidlistdirectory

提问by Francisco

I want to display images of different folders in a GridView, but I don't know what I need to do for get a list with the name of files that are inside a folder in drawable.

我想在 a 中显示不同文件夹的图像GridView,但我不知道我需要做什么才能获得一个包含 drawable 中文件夹内文件名的列表。

回答by Mostafa Jamareh

this method will give you a list containing a list of dir folders and also sub folders:

此方法将为您提供一个包含 dir 文件夹列表和子文件夹列表的列表:

public void listf(String directoryName, ArrayList<File> files) {
File directory = new File(directoryName);

// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
    if (file.isFile()) {
        files.add(file);
    } else if (file.isDirectory()) {
        listf(file.getAbsolutePath(), files);
    }
}
}

回答by Kishor Patil

First Wirte this method in AsyncTask class.

首先在 AsyncTask 类中编写此方法。

private List<File> getListFiles(File parentDir) {
        ArrayList<File> inFiles = new ArrayList<File>();
        File[] files = parentDir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if(file.getName().toString().toLowerCase().contains(fileNameToSearch.toLowerCase()) || file.getName().toString().toUpperCase().contains(fileNameToSearch.toUpperCase())){
                    inFiles.add(file);
                }else {
                    inFiles.addAll(getListFiles(file));
                }
            } else {
                if(file.getName().toString().toLowerCase().contains(fileNameToSearch.toLowerCase()) || file.getName().toString().toUpperCase().contains(fileNameToSearch.toUpperCase())){
                    inFiles.add(file);
                }
            }
        }
        return inFiles;
    }

Call this method from doInBackground(...)

doInBackground(...)

List<File> files = getListFiles(new File(directoryPath));