Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a text file and write to it in Kotlin?

Tags:

android

kotlin

I am new to Kotlin/Android development. I am trying to simply write text to a text file. I simply cannot figure out how to do this. I have tried doing:

File("filename.txt").printWriter().use { out ->
    out.println("${it.key}, ${it.value}")
}

And I got the following. (Side note, "filename.txt" is located in the assets folder in my project)

Caused by: java.io.FileNotFoundException: prices.txt (Read-only file system)

So I figured out that I need to be writing to a spot where I have permission. To my knowledge this is internal private storage. I figured out which directory I have permissions to write to by using:

filesDir

That gave me:

/data/user/com.example.myname.appname/files

So from what I have seen so far I just need to create a file in this directory, write to said file, and read from it when I would like. The problem is I don't know how to do that. But I tried doing this:

// create file?
val file = File(applicationContext.filesDir, "test.txt")
//try to write to said file?
applicationContext.openFileOutput(file.toString(), Context.MODE_PRIVATE).use 
{
    it.write("test".toByteArray())
}

But then I get this error:

Caused by: java.lang.IllegalArgumentException: File    
/data/user/0/com.example.pawlaczykm.dollarsense/files/test.txt contains        
a path separator

I am at the point of maximum misunderstanding and confusion. Again, my goal is to write something to a text file, then access the file later throughout the application.

Update

Tried the following and didn't see back "comment":

File(applicationContext.filesDir, "test.txt").printWriter().use{ out ->
        out.println("content")
    }
File(applicationContext.filesDir, "test.txt").bufferedReader().use{ out ->
        var text5 = out.toString()
        Toast.makeText(this, text5.toString(), Toast.LENGTH_LONG).show()
    }
like image 623
mattp341 Avatar asked Apr 05 '18 16:04

mattp341


1 Answers

openFileOutput() takes a filename, not a path. openFileOutput() returns an OutputStream on a file that is located in the directory identified by getFilesDir() (a.k.a., filesDir in Kotlin).

Try:

File(applicationContext.filesDir, "test.txt").printWriter().use { out ->
    out.println("${it.key}, ${it.value}")
}

or:

applicationContext.openFileOutput("test.txt", Context.MODE_PRIVATE).use 
{
    it.write("test".toByteArray())
}
like image 159
CommonsWare Avatar answered Sep 20 '22 18:09

CommonsWare