user4283875
user4283875

Reputation:

sorting elements File[] array

I'm trying to sort filenames that's in fList array. Originally fList is sorted like this https://i.sstatic.net/OCqJR.jpg and after result https://i.sstatic.net/GgBsq.jpg

I wanted the result sorted according to their preceding number before the filename like so:

...

I have something() method to get the number from fList[x] filename to later compare when doing the swap(fList[x], fList[y]) as you can tell from output console. I'm not sure I understand how File[] actually stores and changes its elements

public static void main(String[] args) {

        File file = new File("pathToFolder");
        File[] fList = file.listFiles();
        for(int x = 0; x < fList.length; x++) {
            int numberX = something(fList[x]);
            for(int y = x; y < fList.length; y++) {
                int numberY = something(fList[y]);
                if(numberX > numberY) {
                    File temp = fList[x];
                    fList[x] = fList[y];
                    fList[y] = temp;
                }
            }
        }
        for(int x = 0; x < fList.length; x++) {         
            System.out.println(fList[x].getName());
        }

    }

    static int something(File file) {
        String temp = file.getName();
        String number = "";
        for(int st = 0; st < temp.length(); st++) {
            if(temp.charAt(st) == '.') break;
            number += temp.charAt(st);
        }
        int fileNumber = Integer.parseInt(number); 
        return fileNumber;
    }

Upvotes: 2

Views: 109

Answers (2)

AElMehdi
AElMehdi

Reputation: 592

Try this if you're using Java8, you can of course tweak it to match your requirements:

List<File> sortedFiles = stream(requireNonNull(file.listFiles()))
            .sorted(File::compareTo)
            .collect(toList());

You can use also the sort method provided by the class Arrays:

File[] sortedFiles = file.listFiles();
    // One liner
    Arrays.sort(sortedFiles);

Both of the solution rely on the implementation of the compareTo from the File class. Link to the official documentation.

I added a test in my personal git repo

Upvotes: 1

Atul Kumbhar
Atul Kumbhar

Reputation: 1083

How about below code:

public static void main(String[] args) {
    File file = new File("pathToFolder");
    File[] fList = file.listFiles();
    Map<Integer, File> fileMap = new TreeMap<Integer, File>();
    for (int x = 0; x < fList.length; x++) {
        int numberX = something(fList[x]);
        fileMap.put(numberX, fList[x]);
    }

    fileMap.forEach((k, v) -> System.out.println((v.getName())));

}

static int something(File file) {
    String temp = file.getName();
    String number = temp.split("\\.")[0];
    int fileNumber = Integer.parseInt(number);
    return fileNumber;
}

Upvotes: 0

Related Questions