Skip to content

Instantly share code, notes, and snippets.

@voquanghoa
Last active March 25, 2019 08:01
Show Gist options
  • Save voquanghoa/9b9fa414b372e3bf1b371ea067ca000e to your computer and use it in GitHub Desktop.
Save voquanghoa/9b9fa414b372e3bf1b371ea067ca000e to your computer and use it in GitHub Desktop.
Snipet to read file from asset/internal storage on Android with Kotlin
import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
/**
* Created by Hoa Vo on 1/18/19.
*/
fun Context.readAssetAsString(fileName: String): String = this.assets.open(fileName).use {
String(it.readBytes())
}
inline fun <reified T: Any> Context.readAsset(fileName: String): T =
Gson().fromJson(this.readAssetAsString(fileName), object: TypeToken<T>() {}.type)
fun Context.readFileAsString(fileName: String): String = this.openFileInput(fileName).use {
String(it.readBytes())
}
inline fun<reified T: Any> Context.readFile(fileName: String): T =
Gson().fromJson(this.readFileAsString(fileName), object: TypeToken<T>() {}.type)
fun Context.writeFile(fileName: String, data: Any){
this.openFileOutput(fileName, Context.MODE_PRIVATE).use { it.write(Gson().toJson(data).toByteArray()) }
}
//Use
articles.addAll(context.readAsset("articles.json"))
...
context.writeFile("data.json", articles);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment