I don't understand the order of the array of files returned by listFiles ()

So, I have a ListView that displays the names of all files in a specific directory. This application also deletes files and adds new files to the directory.

I would like the files to appear in the order they were created, but this is not always true in the .listFiles () file (directory). If I start with an empty directory and start adding files, then the newest file goes to position 0 of the array and goes back to the oldest. However, if I delete any files and then add new ones, things get weird. Here's an example ...

Imagine that I started with an empty directory and added four files to it. The array returned by listFiles () will be:

Position 0 = File # 4 (the fourth will be added)
P 1 = File # 3
P 2 = File # 2
P 3 = File # 1

Then I delete files # 2 and # 3. Array:

P 0 = File # 4
P 1 = File # 1

So far so good. Now I will add two new files. I expect the new array returned by listFiles () to be:

P 0 = File # 6
P 1 = File # 5
P 2 = File # 4
P 3 = File # 1

However, this is what it really is:

P 0 = File # 4
P 1 = File # 6
P 2 = File # 5
P 3 = File # 1

But if I add File # 7, the new array is:

P 0 = File # 7
P 1 = File # 4
P 2 = File # 6
P 3 = File # 5
P 4 = File # 1

Basically, if any files are deleted, the new files will fill their "old positions" in the array. All "old positions" must be filled before new files go to position 0. Can anyone explain this behavior? Also, is there a quick and easy way to re-sort an array of files into my desired chronological order?

+3


source to share


1 answer


Get a list of files - use File.listFiles () , and the documentation states that this makes no guarantees as to the order of files returned. So you need to write a Comparator that uses File.lastModified () and pass that along with an array of files to Arrays.sort () .

CODE:

File[] files = directory.listFiles();

Arrays.sort(files, new Comparator<File>(){
    public int compare(File f1, File f2)
    {
        return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
    } });

      



Try this and let me know what happens.

EDIT:

You can also look at apache commons IO , it has the latest modified comparator built in and many other useful utilities for working with files.

+7


source







All Articles