0

How to run through the folder with subfolders and files and put them in a list of files and a list of directories?

I tried to put only files. I got out, maybe there is a better way?

public List<File> getFileList(String directoryPath, ArrayList<File> files) {
    File directory = new File(directoryPath);
    File[] filesList = directory.listFiles();
    for (File file : filesList) {
        if (file.isFile()) {
            if (!(file.isDirectory())) {
                if (file.getName().substring(file.getName().indexOf(".")).equals(".xml")) {
                    files.add(file);
                }
            }
        } else if (file.isDirectory()) {
            this.getFileList(file.getAbsolutePath(), files);
        }
    }
    return files;
}

I want to have a total of two lists with directories and files.

Ilya Y
  • 744
  • 6
  • 24

1 Answers1

0

A File can't have both File#isDirectory and File#isFile be true a the same time. So this

if (file.isFile()) {
            if (!(file.isDirectory())) {

is not necessary. The first if is enough for a File being a normal file and not a directory.

You try to collect only files that end with .xml. Note that testing the part of the filename starting with the first dot . is not a stable way to do this. Consider a file named foo.bar.baz.xml. Your approach would check for .bar.baz.xml being equal to .xml. Check this answer for how to do this in a stable way.

  • I need .xml files – Ilya Y Jul 06 '19 at 06:58
  • 1
    Yes, that's what I understood. Please note that your code code has a bug that will miss files whose names ends with `.xml` but who contain more than one dot. Check out the answer I've linked to. –  Jul 06 '19 at 06:59
  • 1
    @ILYAYARATS Two other likely bugs: 1/ you will miss anything that ends with ".XML", ".Xml"... 2/ If there is no dot in the name, indexOf returns -1, and substring will throw an exception. The usual way to deal with this: cut at the *last* dot, *if any*, or get the last 4 characters of the name, if there are at least 4 characters. Then convert to lowercase and compare to ".xml". –  Jul 06 '19 at 07:07