Question

I have array of Files in Java as below

File[] fileList = new File("c:/data").listFiles();

The fileList object has files as well as directories. I want to know which order the items will be in the fileList object (files will be at first and then directories or vice versa).

Is the order of items inside the fileList object will remain same everytime or it depends on any factor?

Thanks in advance.

Was it helpful?

Solution 2

The listFiles method, with or without a filter does not guarantee any order.

It does, however, return an array, which you can sort with Arrays.sort().

To get the directories first I would iterate over the array twice extracting the directories using isDirectory

http://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory()

OTHER TIPS

If you have a look at the docs, it clearly explains:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname. If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory. Pathnames denoting the directory itself and the directory's parent directory are not included in the result. Each resulting abstract pathname is constructed from this abstract pathname using the File(File, String) constructor. Therefore if this pathname is absolute then each resulting pathname is absolute; if this pathname is relative then each resulting pathname will be relative to the same directory.

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.

As said in File#listFiles() API, it's recommend to check the APIs when using the methods

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top