DINA TAKLIT
DINA TAKLIT

Reputation: 8388

Kotlin FileWriter does not create any file

Hi I have tried to create file with FileWriter following this tutorial

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

but i always get

   not fn

once i open the logcat which means that the file is never created.

I have not understood the matter.

Here is my code

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")
            }

        }
    }
}

Upvotes: 0

Views: 2839

Answers (1)

Mark
Mark

Reputation: 9919

Changing the code to this :

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

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

Should solve the issue. You should provide the directory where you want the file placed. Also you can use writer.use { it.write(strJson)} as FileWriter implements Closeable - this handles closing the writer regardless of exception.

Upvotes: 7

Related Questions