Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing to file in a directory in Android (Kotlin)

I have a json string I would like to write to a file in the internal storage, as it will serve as the app’s savefile. Since there will be several of them, I want all the files to be inside a directory called savefiles, that should be also created, if not found. I tried to achieve this using OutputStreamWriter, first I generate the file’s path and then try to write to it. Here’s the code:

        try {
            val path = "savefiles/${SimpleDateFormat("yyyyMMddHHmmss").format(Date())}.json"
            val outputStreamWriter = OutputStreamWriter(openFileOutput(path, Context.MODE_PRIVATE))
            outputStreamWriter.write(myJson.toString())
            outputStreamWriter.close()
        } catch (e: IOException) {
            Log.e("Exception", "File write failed: $e")
        }

However, this gives me the error: java.lang.IllegalArgumentException: File /savefiles/20230708174147.json contains a path separator

I have come to understand that I shouldn’t include the name of the directory in the path string, but haven’t been able to find a way around.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To create a directory and write a file inside it in the internal storage of an Android device using Kotlin, you can follow these steps:

Here’s the complete code snippet that incorporates the above steps:

val directory = File(context.filesDir, "savefiles")
if (!directory.exists()) {
    directory.mkdirs()
}

val fileName = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(Date()) + ".json"
val file = File(directory, fileName)

try {
    val outputStream = FileOutputStream(file)
    outputStream.write(myJson.toString().toByteArray())
    outputStream.close()
} catch (e: IOException) {
    Log.e("Exception", "File write failed: $e")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading