我想通過添加帶有他的姓名和日期串列的標題來更改我的 CSV 格式檔案
這是我嘗試過的,它看起來像這樣:

fun export(path: File?) {
CoroutineScope(Dispatchers.IO).launch {
selected?.let { it ->
val file = File(path, "${it.name}.csv")
val tags = repository.getTagsOfList(it.id.toInt())
val tagsCSV = "TAG: ${tags.map { it.name }}; DATE: ${tags.map { it.date }}"
file.writeText(
"LIST NAME: ${it.name}; "
tagsCSV)
val csv = file.readText()
println(csv)
}
}
}
但我想要這種格式:

編輯: 我使用了 apache-commons.csv,它更容易,但我有一個例外:
CoroutineScope(Dispatchers.IO).launch {
selected?.let { it ->
val file = "${it.name}.csv"
val writer = Files.newBufferedWriter(Paths.get(file))
val csvPrinter =
CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("LIST NAME;TAGS;DATE"))
val tags = repository.getTagsOfList(it.id.toInt())
// push the values into the file.
csvPrinter.printRecord(
"${it.name};${tags.map { it.name }};${tags.map { it.date }}")
//pushes the file and its content into the local system
csvPrinter.flush()
csvPrinter.close()
println(csvPrinter)
}
}
}
FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: fr.pageup.techcare.readapp.debug, PID: 11435
java.nio.file.FileSystemException: yuyu.csv: Read-only file system
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434)
uj5u.com熱心網友回復:
問題是您沒有嘗試在每個示例中在同一位置創建檔案。
當您自己撰寫檔案時,您將“name.csv”附加到回傳的路徑getExternalFilesDir("lists")
在 apache csv 示例中,您根本不使用getExternalFilesDir("lists")您嘗試寫入行程的當前作業目錄的值,該目錄是不同的位置getExternalFilesDir("lists")
我不是 kotlin 專家,但嘗試替換
val file = "${it.name}.csv"
val writer = Files.newBufferedWriter(Paths.get(file))
和
val file = File(path, "${it.name}.csv")
file.bufferedWriter().use {
val csvPrinter .... // rest of writing code here
}
這樣,您打開緩沖寫入器的位置具有path預先添加的值,如第一個示例中所示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/464542.html
