plaidshirt
plaidshirt

Reputation: 5671

Sort array of filepaths by filename

I use directory.listFiles() to get list of files recursively from a given directory structure. I tried to use following codes for this purpose, but none of them are working.

    Arrays.sort(fList, Comparator.comparing(File::getName));
    Arrays.sort(fList, NameFileComparator.NAME_COMPARATOR);

Files should be listed in ascending order from all the subdirectories.

Upvotes: 0

Views: 1300

Answers (3)

gil.fernandes
gil.fernandes

Reputation: 14601

If you want to sort all the file paths recursively in a tree structure, you can try Files.walk using sorted with a Java 8 stream:

List<String> files = Files.walk(Paths.get("/tmp"))
                         .filter(Files::isRegularFile) // Check you have only file names
                         .map(Path::toString) // map to string
                         .sorted() // sort
                         .collect(Collectors.toList()); // create list

If you want case insensitive sorting:

List<String> files = Files.walk(Paths.get("d:/tmp"))
                         .filter(Files::isRegularFile) // Check you have only file names
                         .map(Path::toString) // map to string
                         .sorted(Comparator.comparing(String::toLowerCase)) // sort case insensitive
                         .collect(Collectors.toList()); // create list

Upvotes: 2

keksimus.maximus
keksimus.maximus

Reputation: 373

To list all files within directory and subdirectories use Apache Commons FilesUtil.listFiles method

Collection<File> fCollection = FileUtils.listFiles(directory, null, true);
File[] fList = fCollection.toArray(new File[fCollection.size()]);

Then to sort the array you can just use

Arrays.sort(fList);

Upvotes: 1

Srinivasan Sekar
Srinivasan Sekar

Reputation: 2119

File is a comparable class, which by default sorts pathnames lexicographically. Just use ,

 Arrays.sort(fList);

If you want to sort them differently, you can define your own comparator.

Upvotes: 5

Related Questions