获取目录中的所有文件并将其插入到列表中

时间:2018-10-16 00:46:44

标签: java android

我正在尝试将所有文​​件放入目录中,然后插入List中,但出现错误:

  列表中的

add()无法应用于(Java.io.File)

这是我的代码:

fragmentList.java

public List<mList> pList;



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

    // Get all files from a directory.
    File[] fList = directory.listFiles();
    if(fList != null)
        for (File file : fList) {
            if (file.isFile()) {
                pList.add(file); // THE ERROR IS HERE
            } else if (file.isDirectory()) {
                listf(file.getAbsolutePath());
            }
        }
}

2 个答案:

答案 0 :(得分:0)

如果要将File元素添加到列表中

更改

public List<mList> pList;

public List<File> pList;

或如您所说要获取文件名

更改

public List<mList> pList;

public List<String> pList;

并使用file.getName();

添加元素

答案 1 :(得分:-2)

public void getFileList() {
    // list will have all files in directory.
    List<File> pList = new ArrayList<>();
    // calling listf method with directoryFull path as input 
    listf(pList, "/TESTDIR");
    // printing All files path on console 
    System.out.println(" files " + pList);

}

// Method will take directory path and list as input , It recursively collect 
// all files in directory inside pList.
public static void listf(List<File> pList, String directoryName) {
    File directory = new File(directoryName);

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