Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

listing files in a sorted order

 
sri chitra
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method File[] listFiles() will return back an array of
file objects. But I want to have the array sorted alphabetically.
How can it be done?
 
James Swan
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
you could investigate the java.util.Arrays or java.util.Collections APIs. They have various methods for performing sorting on arrays or lists.
I tried the following code:

When run under windows, the File[] is already sorted for you, but when run under Unix I needed to add the call to Arrays.sort(Object[]).
If the desired sorting isn't what you are after then you will have to define your own custom sorting by implementing Comparator and calling something like Arrays.sort(Object[] myArray, Comparator myComparator).
James.
 
sri chitra
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply.
I got the alphabetically sorted list by using Arrays.sort(Object[])
Thanks again
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic