Home > OS >  How to get an alphabetically sorted list of files in Kotlin?
How to get an alphabetically sorted list of files in Kotlin?

Time:04-16

So I have a bunch of text files the contents of I need to read and print out to a textview. I am currently using .list() (java.io.File) to get the list (it outputs an Array of filename strings) of files in a given directory. I then iterate through the array and read the contents one by one.

The problem is, I need to order the files descending alphabetically (the files are logs and I need to show the newest log first - the filenames are timestamps - (e.g. 20220414221311) - YYYYMMDDHHMMSS).

The .list function seems to order them randomly.

I have tried putting the names in a List and then sort it, but it did not work. Can anyone help?

Here is the code without any ordering:

    fun ui() {

    setContentView(R.layout.activity_main)

    val dir = getExternalFilesDir(null);
    val attendancedir = File("$dir/attendance")
    var attendancelist = attendancedir.list()

    val scroll = findViewById<View>(R.id.SCROLL) as LinearLayout

    for (attendancefile in attendancelist) {

        val attendancedisplay = File("$dir/attendance/$attendancefile")

        val tv = TextView(this)
        tv.text = attendancedisplay.readText()
        scroll.addView(tv)
        }

CodePudding user response:

If you need sort your list with alphabetical order, you can use Kotlin operators sortWith and compareTo. It should looks like:

attendancelist.sortWith { text1, text2 -> 
    text1.compareTo(text2, ignoreCase = true) 
}

But if you need sort list according to your timestamp 'YYYYMMDDHHMMSS', I can suggest next steps:

  1. Convert your string list to date list.
  2. Sort date list.
  3. Convert date list back to string list(or operate date list).

Next sample of code:

private val sdf = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
private fun ui() {
    val dir = getExternalFilesDir(null);
    val attendancedir = File("$dir/attendance")
    val attendancelist = attendancedir.list()
    val sortedList = getSortedList(attendancelist)

    // do operations with sortedList
}

private fun getSortedList(attendancelist: Array<out String>):  List<String?> {
    return attendancelist.map { text -> // convert your string list to date list
        sdf.parse(text)
    }.sortedWith { date1, date2 -> // sort date list
        date1.compareTo(date2)
    }.map { date -> // convert date list back to string list
        date?.let { sdf.format(it) }
    }
}
  • Related