I want to change my CSV format file by adding a header with his list of names and date
here is what I tried and it looks like this :
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)
}
}
}
but I want this format:
EDIT: I used apache-commons.csv, it's easier but i have an exception :
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)
CodePudding user response:
The problem is you are not trying to create the file in the same location in each example.
When you wrote the file yourself you append the "name.csv" to the path returned by getExternalFilesDir("lists")
In the apache csv example you do not use the value of getExternalFilesDir("lists")
at all you are trying to write to the current working directory of the process which is a different location to getExternalFilesDir("lists")
I'm not a kotlin expert but try replacing
val file = "${it.name}.csv"
val writer = Files.newBufferedWriter(Paths.get(file))
with
val file = File(path, "${it.name}.csv")
file.bufferedWriter().use {
val csvPrinter .... // rest of writing code here
}
This way the location you are opening the buffered writer at has the value of path
prepended to it as in the first example