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