The main problem you're having is you've not initialized allFiles before using it...
File[] list = source.listFiles(filter);
if (list != null) {
for (File f : list) {
//...
// still null
allFiles[i] = f; // it is giving nullpointerexception
You could use allFiles = new File[list.length], but the problem here is you could end up with null elements in the list, as you are filtering out elements...
Instead, you could use your FileFilter, that's what it's there for...for example...
public File[] findFiles(File source) {
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File pathname) {
return !pathname.isHidden() &&
pathname.getName().toLowerCase().endsWith(".txt");
}
};
File[] list = source.listFiles(filter);
return list;
}
Basically, what this does is checks to see if the file is not hidden and if its name ends with .txt, as an example...
Updated
Because you're doing a recursive look up, you really need some way to add new files to your array and grow it dynamically.
While you can do this with plain old arrays, some kind of List would be much easier, for example...
The following uses the FileFilter to find all non-hidden files that directories or end in .txt
It then sorts the resulting list of files, so that the "files" appear first and the "directories" or sorted to the bottom, this is a nit pick, but ensure a certain order of files in the list.
It then processes the file list, adding the "files" to the List and recurisivly scanning the "directories", adding the results to the List...
public static File[] findFiles(File source) {
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File pathname) {
return !pathname.isHidden() &&
(pathname.isDirectory() ||
pathname.getName().toLowerCase().endsWith(".txt"));
}
};
File[] files = source.listFiles(filter);
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
int compare = 0;
if (o1.isDirectory() && o2.isDirectory()) {
compare = 0;
} else if (o1.isFile()) {
compare = -1;
} else {
compare = 1;
}
return compare;
}
});
List<File> fileList = new ArrayList<>(25);
for (File file : files) {
if (file.isFile()) {
fileList.add(file);
} else {
fileList.addAll(Arrays.asList(findFiles(file)));
}
}
return fileList.toArray(new File[fileList.size()]);
}
As an example...