0

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.

  • Is your issue just the order? If so you should probably Arrays.sort your array before processing it –  Apr 22 '14 at 21:22
  • Because that's exactly how the underlying OS is returning them, lexically sorted. If that's not the order you want, you'd need to get all the filenames and sort them the way you *do* want them. – Brian Roach Apr 22 '14 at 21:24

2 Answers2

0

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.

numX
  • 830
  • 7
  • 24
  • The first paragraph of your answer is ok, though technically it's *lexicographical*. The second part ... not so much. You just sort the array with a comparator that produces the order you want. – Brian Roach Apr 22 '14 at 21:27
  • I thought my solution was simpler to having to create a comparator that sorts all string in numerical order, rather than lexographical. – numX Apr 22 '14 at 21:33
0

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()));
Community
  • 1
  • 1
Simon
  • 26
  • 3