1

I'm writing a code where in there a bunch of files that have to be taken as input from a directory.

The program works fine, but the problem comes up in the way the files are picked. In my directory when I do a sort the first file shown is file5521.3, but in my program the first file that is picked up is file5521.100. THis is pretty confusing.

I've also tried using Arrays.sort(list, NameFileComparator.NAME_COMPARATOR), but it also gives the same result as previous.

Below is my code.

void countFilesInDirectory(File directory, String inputPath) throws IOException {
    File[] list = directory.listFiles();
    Arrays.sort(list, NameFileComparator.NAME_COMPARATOR);
    for (int i = 0; i < list.length; i++) {
        System.out.println(list[i]);
    }
    tempPath = inputPath.substring(0, inputPath.lastIndexOf("\\") + 1) + "OP\\";
    File outPath = new File(tempPath);
    if (!outPath.exists()) {
        outPath.mkdir();
    }
    File temp = new File(tempPath + "temp.txt");
    FileOutputStream fos = new FileOutputStream(temp);

    if (!temp.exists()) {
        temp.createNewFile();
    }
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    for (int i = 0; i < list.length; i++) {
        System.out.println(list[i]);
        setStatusText(i);
        GenerateFiles(list[i].getAbsoluteFile().toString(), bw);
    }
    bw.write("</body>");
    bw.close();
    File newFile = new File(temp.getParent(), "Index.html");
    Files.move(temp.toPath(), newFile.toPath());
}

please let me know how can I do this.

Working Solution with Last Modified Date

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

The Comparator works fine with last modified date, but when I try it with below code. The result is same as previous.

Arrays.sort(list, new Comparator<File>() {

            @Override
            public int compare(File o1, File o2) {
                return o1.getName().compareTo(o2.getName());
            }

        });

In my Windows Explorer It looks like below. I've sorted the filenames.

enter image description here

And my console output shows the below.

enter image description here

Thanks

Rakesh
  • 564
  • 1
  • 8
  • 25
  • Why does the order of processing matter? And if it does, then the file name convention should reflect that to avoid differences in directory and string based sorting so that it is unequivocally the same. – ManoDestra Apr 01 '16 at 15:15
  • what is your OS, what do you mean by "In my directory **when I do a sort** the first file shown is"? –  Apr 01 '16 at 15:17
  • The order of files is going to be determined by whatever software you use to view them (e.g. Explorer on Windows). You'll need to use a comparator that uses that same logic. – resueman Apr 01 '16 at 15:18
  • Hi @RC. I mean that In my Windows Explorer when I click the title bar, the names gets sorted. – Rakesh Apr 03 '16 at 07:26

2 Answers2

1

If your OS is Windows XP or later, your files will be sorted using Numerical File Name Sorting.

Since you want to match the file order both in the program and in your File Explorer, you can either:

  1. Follow the steps in the link to use Classical Literal Sorting which will change the way File Explorer displays files.
  2. Create a custom Comparator that you pass into sort that will sort based on the actual VALUE of the number (e.g. 3 would come before 10 because 3 < 10)
Chara
  • 1,045
  • 10
  • 21
1

You can use Apache Commons IO to sort files using many predefined Comparators or even combine these using CompositeFileComparator

Here is an example:

import org.apache.commons.io.comparator.*;

File dir = new File(".");
File[] files = dir.listFiles();
File[] filesSorted = DefaultFileComparator.DEFAULT_COMPARATOR.sort(files);
File[] filesReversed = DefaultFileComparator.DEFAULT_REVERSE.sort(files);

... and here is the list of available comparators

diginoise
  • 7,352
  • 2
  • 31
  • 39
  • When I do this, it is throwing me some error Saying `The method sort(File[]) is undefined for the type Comparator` – Rakesh Apr 03 '16 at 07:19
  • Hi friend, I've updated my question with the code that I've tried. Can you please look into it. – Rakesh Apr 03 '16 at 07:29
  • @Rakesh what you see is the result of lexical sort. Sorting strings using lexical sorts makes the following A1 < A11 < A11112 < A12 < A9. Windows file browser is not using lexical order but natural ordering (when seeing numbers in parts of text it will use numerical ordering. You would have to create your own comparator implementing human natural order sorting. See this question: http://stackoverflow.com/questions/7270447/java-string-number-comparator – diginoise Apr 26 '16 at 09:46