Skip to content

Instantly share code, notes, and snippets.

@salamanders
Created October 21, 2017 02:42
Show Gist options
  • Save salamanders/519d19fcca32d11ce920a3883ce7dcc1 to your computer and use it in GitHub Desktop.
Save salamanders/519d19fcca32d11ce920a3883ce7dcc1 to your computer and use it in GitHub Desktop.
Kotlin functions to allow persisting a Set<Serializable> to/from zipped file (good for prototyping and restarting processes)
/** Save/load any Set<Serializable>, works easily with your simple data class */
inline fun Set<out Serializable>.save(fileName:String="persist_${javaClass.simpleName}.ser.gz") {
val tmpPath = Files.createTempFile(fileName, ".tmp")
ObjectOutputStream(GZIPOutputStream(Files.newOutputStream(tmpPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE))).use {
println("Persisting Set<${javaClass.simpleName}> to $fileName containing ${this.size} entries.")
it.writeObject(this)
}
Files.move(tmpPath, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING)
}
inline fun <reified T> MutableSet<in T>.load(fileName:String="persist_${javaClass.simpleName}.ser.gz") {
try {
ObjectInputStream(GZIPInputStream(FileInputStream(fileName))).use {
val loaded = it.readObject() as Collection<*>
println("Loading collection with ${loaded.size} entries.")
loaded.forEach { if (it !is T) throw IllegalArgumentException() }
this.addAll(loaded.filterIsInstance<T>())
}
} catch (e:IOException) {
println("Unable to load($fileName): ${e.localizedMessage}")
}
}
// Customize to your needs
data class YourDataClass(val sourceFile: String, val frame: Int, val x: Int, val y: Int, val width: Int, val height: Int) : Serializable
// Long running app has
val yourStuff = mutableSetOf<YourDataClass>()
yourStuff.load()
// Skip doing stuff that is already done, do new stuff, and every so often persist with
yourStuff.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment