我已经学会了如何在这个链接中导出CSV文件,但我在android API 30+中导出有问题。我试过用MediaStore写文件,但是没有运气。
ExportService.kt问题
object ExportService {
fun <T : Exportable> export(context: Context, type: Exports, content: List<T>): Flow<Boolean> =
when (type) {
is Exports.CSV -> writeToCSV<T>(context, type.csvConfig, content)
}
private fun <T : Exportable> writeToCSV(
context: Context,
csvConfig: CsvConfig,
content: List<T>
) =
flow {
with(csvConfig) {
val collection = sdk29AndUp {
MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} ?: MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL)
val values = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, filename)
put(MediaStore.MediaColumns.MIME_TYPE, "text/csv")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(
MediaStore.MediaColumns.RELATIVE_PATH,
Environment.DIRECTORY_DOCUMENTS + "/Medisy's Clinic/"
)
}
}
val uri = context.contentResolver.insert(collection, values)
Log.e("TAG", "writeToCSV: ${uri!!.path} $filename")
val csvWriter = CSVWriter(FileWriter(uri!!.path?.let { File(it) }))
StatefulBeanToCsvBuilder<T>(csvWriter)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.build()
.write(content)
csvWriter.close()
}
emit(true)
}
}
输出日志
E/TAG: writeToCSV: /external_primary/file/40 Medisy's Clinics-May_31_2022_10:58:58_AM.csv
W/System.err: java.io.FileNotFoundException: /external_primary/file/40: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
W/System.err: at com.example.medisyclinics.data.csv.ExportService$writeToCSV$1.invokeSuspend(ExportService.kt:47)
谁能给我解答?
我用environment . getexternalstoragediretory()函数解决了这个问题