简体   繁体   中英

How convert data to csv file in Kotlin (Android)

  1. I want to convert some data to csv file. It's my goal.

  2. I can not do it. I have found solution but it's work only for small data. I have a problem when I use this solution for big data.

  3. This is my solution.

     val path = context.getExternalFilesDir(null) val letDirectory = File(path, "data") letDirectory.mkdirs() val file3 = File(letDirectory, "out777.csv") val writer = FileWriter(file, true) writer.append("Name") writer.append(',') writer.append("Adress") writer.append('\n') writer.flush() writer.close()

But my solution does not work (work bad) when I use it inside big loop (inside big list).

    val path = context.getExternalFilesDir(null)
    val letDirectory = File(path, "data")
    letDirectory.mkdirs()
    val file3 = File(letDirectory, "out777.csv")
    val writer = FileWriter(file, true)
    
    for (l in listName){
    writer.append(l.name)
    writer.append(',')
    writer.append(l.adres),
    writer.append(',')
    writer.append(l.code),
    ...
    writer.append('\n')
    }
    writer.flush()
    writer.close()

If my list listName is a big I have problem with my phone if I use this idea to copy all data to csv file on my phone. For example, now I have problem with my phone (with file system) maybe my file system has some problem because I use this idea to cope csv file from phone to PC.

How can I improve my solution to work with big list inside loop if I want to append a lot of rows to csv file.

Check this post - https://www.baeldung.com/kotlin/csv-files - it contains a few nice references to some libraries or pure Kotlin approaches if you prefer to use those.

Applying it to your use case, maybe something like:

fun OutputStream.writeCsv(context: Context, listOfData: List<YourData>) {
    //get data create directory
   ......

    val writer = bufferedWriter()
    writer.write(""""Name", "Address", "Code"""")
    writer.newLine()
    listOfData.forEach {
        writer.write("${it.name}, ${it.address}, \"${it.code}\"")
        writer.newLine()
    }
    writer.flush()
    writer.close()
}

And then call this where you need it,

FileOutputStream("out777.cs").apply { writeCsv(listOfData) }

One thing to note here is using bufferedWriter:

FileWriter writes directly into Files and should be used only when the number of writes is less. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better.

Not tested but this might point you in a more cleaner and efficient solution. There are also some libraries specifically for this. Take a look

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM