Home > OS >  How to write data to file in Kotlin
How to write data to file in Kotlin

Time:07-06

A little while ago, i started learning Kotlin, and i have done it's basics, variables, classes, lists and arrays etc. but the book i was learning from seemed to miss one important aspect, reading and writing to a file, maybe a function like "fwrite" in C

So i searched google, and yes, reading and writing bytes was easy enough. However, me being used to C 's open personality, wanted to make a "kind of" database.

In C i would simply make a struct and keep appending it to a file, and then read all the stored objects one by one, by placing "fread" in a for loop or just reading into an array of the struct in one go, as the struct was simply just the bytes allocated to the variables inside it.

However in Kotlin, there is no struct, instead we use Data Class to group data. I was hoping there was an equally easy way to store data in a file in form of Data Class, and read it into maybe a List of that class, or if that is not possible, maybe some other way to store grouped data which would be easy to read and write.

CodePudding user response:

Easiest way is to use a serialization library. Kotlin already provides something for that

TL;DR;

Add KotlinX Serialization to your project, choose the serialization format you prefer (protobuf or cbor will fit, go for json if you prefer something more human readable although bigger in size), use the proper serializer for generating your ByteArray and write it to a file using Kotlin methods for that

Generating the ByteArray might be tricky, not sure as I'm telling this from memory. What I can tell for sure is that if you choose JSON you can get the string representation and write to a file. So I'm assuming the same will be valid for binary formats (but writing to a file in binary instead of strings)

CodePudding user response:

What you need can be fulfilled by ROOM DATABASE

It is officially recommended by GOOGLE, It uses your Android application's internal Database which is made using SQLITE

You can read more info about ROOM at

https://developer.android.com/jetpack/androidx/releases/room?gclid=Cj0KCQjw5ZSWBhCVARIsALERCvwjmJqiRPAnSYjhOzhPXg8dJEYnqKVgcRxSmHRKoyCpnWAPQIWD4gAaAlBnEALw_wcB&gclsrc=aw.ds

It provided Data Object Class (DAO) and Entity Classes through which one can access the database TABLE using SQL Queries.

Also, it will check your queries at compile time for any errors in it.

Note: You need to have basic SQL Knowledge for building the queries for CRUD Operations

  • Related