当我使用bufferedWriter()写入CSV时,使用foreach时出现错误

问题描述 投票:0回答:1

我正在创建一个使用 Kotlin 将数据保存为 CSV 格式的程序。(在 Android 中)

我想使用bufferedWriter()来存储变量中存储的数据。

如果我在函数内使用forceach作为迭代语句,则不会存储所有数据并返回异常。当不使用 foreach 并使用另一个迭代时,它不会返回异常。

我想知道为什么会出现这种现象。

private fun OutputStream.writeCsv(data: List<BlinkMonitoringTestData>) {

    val writer = bufferedWriter()

    try {
        writer.write(""""time", "distance", ..."""") // 36 columns
        writer.newLine()

        // if you use this, return exception.
        //data.forEach { // repeat about 900 ~ 1200 times
        //    writer.write("${it.time}, ${it.distance}, ...")
        //    writer.newLine()
        //}

        // if you use this, success
        repeat(data.size){ index -> // repeat about 900 ~ 1200 times
            writer.write("${data[index].time}, ${data[index].distance}, ...")
            writer.newLine()
        }

        writer.flush()
    } catch(e : Exception) {
        Log.w("CustomCheck", "CSV Save Error")
        Toast.makeText(context, "CSV Save Error", Toast.LENGTH_LONG).show()
    } finally {
        writer.close()
    }

}

另外,异常中的错误信息返回null。

我想知道为什么会这样。是缓冲问题吗?

android kotlin csv foreach buffer
1个回答
0
投票

添加 StackTace

java.util.ConcurrentModificationException 在 java.util.ArrayList$Itr.next(ArrayList.java:860) 在 com.ljh.prototype2401.presentation.viewmodel.BlinkMonitoringViewModel.writeCsv(BlinkMonitoringViewModel.kt:267) 在 com.ljh.prototype2401.presentation.viewmodel.BlinkMonitoringViewModel.saveCSV(BlinkMonitoringViewModel.kt:103) 在 com.ljh.prototype2401.presentation.viewmodel.BlinkMonitoringViewModel.endTest(BlinkMonitoringViewModel.kt:49) 在 com.ljh.prototype2401.presentation.view.BlinkMonitoringTestViewKt$BlinkMonitoringTestView$2$1$4$1.invoke$lambda$2$lambda$0(BlinkMonitoringTestView.kt:284) 在 com.ljh.prototype2401.presentation.view.BlinkMonitoringTestViewKt$BlinkMonitoringTestView$2$1$4$1.$r8$lambda$fy3VAAiHjeekfz98h6LFvIjI-20(未知 来源:0) 在 com.ljh.prototype2401.presentation.view.BlinkMonitoringTestViewKt$BlinkMonitoringTestView$2$1$4$1$$ExternalSyntheticLambda0.onCompletion(未知 来源:6) 在 android.widget.VideoView$3.onCompletion(VideoView.java:550) 在 android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:4019) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loopOnce(Looper.java:226) 在 android.os.Looper.loop(Looper.java:313) 在 android.app.ActivityThread.main(ActivityThread.java:8762) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)

© www.soinside.com 2019 - 2024. All rights reserved.