Kishore_2021
Kishore_2021

Reputation: 689

How to get java.io.File.list() same order as in Windows Explorer

How to get java.io.File.list() same order as in Windows Explorer?

In a program I am creating the Temp folders e.g. Temp1, Temp2 and so on. But when I use java.io.File.list() to retrieve the folder list, it gives as Temp1, Temp10 and so on.

Please tell how to get the same order list as showing in Windows Explorer?

Thanks

Upvotes: 1

Views: 1187

Answers (3)

wumpz
wumpz

Reputation: 9141

This is an implementation of this specific windows sorting algorithm called natural sort.

Java - Sort Strings like Windows Explorer

In short it splits the two Strings to compare in Letter - Digit Parts and compares this parts in a specific way to achieve this kind of sorting.

Upvotes: 0

Dave Keen
Dave Keen

Reputation: 1

You would need to write your own Comparator. The Comparator would need to split the file name strings, separating them into sequences of consecutive non-numeric characters and of numeric characters. Then sort the sequences, converting a sequence of numeric characters to an integer before comparing. Also, if the integers are equal (due to leading zeroes), then order the longer numeric sequence before the shorter sequence.

Upvotes: 0

MoveFast
MoveFast

Reputation: 3015

Windows Explorer shows the files sorted by name by default. Looking at javadoc for File.list(),

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

So after getting the file list using File.list(), you need to sort this by file names Arrays.sort(file.list()) to get the required order.

Upvotes: 5

Related Questions