How can I sort files in a directory in java?

前端 未结 2 1260
北荒
北荒 2020-12-06 22:14

Here is my code and it works ! But I want to be able to sort the files list according to name, size, modification date and more

import java.io.File;
import o         


        
2条回答
  •  没有蜡笔的小新
    2020-12-06 22:40

    Arrays.sort( files, new Comparator() {
        public int compare( File a, File b ) {
            // do your comparison here returning -1 if a is before b, 0 if same, 1 if a is after b
        }
    } );
    

    You could define a bunch of different Comparator classes to do different comparisons like such:

    public class FileNameComparator implements Comparator {
        public int compare( File a, File b ) {
            return a.getName().compareTo( b.getName() );
        }
    }
    
    public class FileSizeComparator implements Comparator {
        public int compare( File a, File b ) {
            int aSize = a.getSize();
            int bSize = b.getSize();
            if ( aSize == bSize ) {
                return 0;
            }
            else {
                return Integer.compare(aSize, bSize);
            }
        }
    }
    
    ...
    

    Then you would just swap em out:

    Arrays.sort( files, new FileNameComparator() );
    

    or

    Arrays.sort( files, new FileSizeComparator() );
    

提交回复
热议问题