Kotlin FileWriter不会创建任何文件

DIN*_*LIT 0 android file filewriter kotlin

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

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

但我总是得到

   not fn
Run Code Online (Sandbox Code Playgroud)

一旦我打开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")
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*een 5

将代码更改为:

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

    } catch (e : IOException){
        Log.e("errr","not fn", e)
    }
Run Code Online (Sandbox Code Playgroud)

应该解决这个问题.您应该提供放置文件的目录.您也可以使用writer.use { it.write(strJson)}作为FileWriter工具Closeable-无论它处理关闭异常的作家.