我正在尝试将所有文件放入目录中,然后插入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());
}
}
}
答案 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());
}
}
}