【问题标题】:Kotlin FileWriter does not create any fileKotlin FileWriter 不创建任何文件
【发布时间】:2018-10-22 21:08:16
【问题描述】:

您好,我已尝试按照本教程使用 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")
            }

        }
    }
}

【问题讨论】:

  • 您可能想要这样的FileWriter(File(context.filesDir, "data.json")) - 您应该提供您想要放置文件的目录。你也可以使用writer.use { it.write(strJson)} 作为FileWriter 实现Closeable - 这将处理关闭编写器而不管异常。
  • 你的意思是给目录的名字
  • 我怎么能感谢你我把这个writer= FileWriter(File(this.filesDir, "data.json")) 和它的工作原理。请回答这个问题,其他人也可以得到好处。上帝保佑你
  • 如果我真的撒谎,你说过我省略了所有的 tryes 和 cach。你能更新解决方案吗。再次感谢

标签: android file kotlin filewriter


【解决方案1】:

把代码改成这样:

    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 - 这将处理关闭编写器而不管异常。

【讨论】:

  • 现在没有理由在 try 块之外将 writer 声明为可空且可变。
猜你喜欢
  • 1970-01-01
  • 2017-12-28
  • 2014-10-07
  • 1970-01-01
  • 2020-09-29
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
相关资源
最近更新 更多