Frage

I am trying to read files from a folder to java, I found this snippet and used it.

File folder = new File("Z..");
    File[] listOfFiles = folder.listFiles();



for (int i = 0; i < listOfFiles.length; i++) {
      File file = listOfFiles[i];
      if (file.isFile() && file.getName().endsWith(".txt")) {
       String content = FileUtils.readFileToString(file);

    }

This works fine except it doesn't retrieve the files in order. I have files numbered file 0,file 1, file2.....file10 and how it retrieves it file 0 file 1 file 10 and then file 2, What should I to retrieve it in proper series. Should I be using something else? I'm new to this.

War es hilfreich?

Lösung

There is a great example of using a custom comparator to sort an array of files here: Best way to list files in Java, sorted by date last modified

You would have to modify the return of the comparator to be along the lines of

return f1.getName().compareTo(f2.getName());

and it should be exactly what you're looking for.

If all your files are numbered you may want to compare the file names as integers:

return Integer.valueOf(f1.getName()).compareTo(Integer.valueOf(f2.getName()));

Andere Tipps

The files are being read in alphabetical order. Alphabetically, 10 comes before 2 since the first letter in both is first compared i.e. '1' with '2' .

To solve this you could parse the numbers, link each number to the original file name and then sort the numbers and read them in the new order.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top