Kotlin FileWriter 不创建任何文件

Kotlin FileWriter does not create any file

您好,我尝试按照本教程使用 FileWriter 创建文件

https://medium.com/@ssaurel/parse-and-write-json-data-in-java-with-gson-dd8d1285b28

但我总是得到

   not fn

一旦我打开 logcat,这意味着文件永远不会被创建。

没看懂

这是我的代码

fun writeJson()
{
    val item1 = InterItem(1, DateT(2018, Calendar.FEBRUARY, 6).date, "Dina", "type1")
    val  item2 = InterItem(2, DateT(2018, Calendar.MARCH, 8).date, "Lili", "type2")
    val item3= InterItem(3, DateT(2018, Calendar.MAY, 10).date, "Wassim", "type3")
    val res =  ListInter()
    res.list= arrayListOf( item1, item2, item3)
    val gson = GsonBuilder().setPrettyPrinting().create()
    val strJson = gson.toJson(res)
    var writer: FileWriter? = null
    try {
        writer = FileWriter("data.json")
        writer.write(strJson)
    } catch (e: IOException) {
        e.printStackTrace()
        Log.e("errr","not fn")
    } finally {
        if (writer != null) {
            try {
                writer.close()
            } catch (e: IOException) {
                e.printStackTrace()
                Log.e("errr","not close")
            }

        }
    }
}

将代码更改为:

    try {
        val writer = FileWriter(File(this.filesDir, "data.json"))
        writer.use { it.write(strJson) }

    } catch (e : IOException){
        Log.e("errr","not fn", e)
    }

应该可以解决问题。您应该提供要放置文件的目录。您也可以使用 writer.use { it.write(strJson)} 作为 FileWriter 实现 Closeable - 无论异常如何处理关闭编写器。