【发布时间】: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