Home > Enterprise >  read file into arrayListOf
read file into arrayListOf

Time:03-07

The file Name.txt contains 3 names and I would like to put this names inside an arrayListOf.

    val calsaveclient_name = "Names"
    val path = this.getExternalFilesDir(null)
    val filename:String = "$calsaveclient_name.txt"
    val file = File(path, filename)
    var namearray1 = ""

    val reader = BufferedReader(FileReader(file))
    reader.lines().forEach {
        namearray1 = it
        println("names: $namearray1")

    }
    
    
    val namearray = arrayListOf<String>(
        namearray1
    )

    println("Final Names: $namearray")

}

CodePudding user response:

You're creating more variables than you need. You can directly read the lines into a List.

val calsaveclient_name = "Names"
val path = this.getExternalFilesDir(null)
val filename:String = "$calsaveclient_name.txt"
val file = File(path, filename)

val nameList = file.readLines()

println("Final Names: $nameList")

If you specifically need an ArrayList instead of List (you probably don't), you can wrap the list in an ArrayList constructor call.

val nameArrayList = ArrayList(file.readLines())
  • Related