Clean up MarkdownFile Kotlin implementation

This commit is contained in:
Billy Brawner 2019-08-15 18:39:35 -05:00 committed by William Brawner
parent efe85b5b80
commit 5595ca7ee3

View file

@ -1,61 +1,34 @@
package com.wbrawner.simplemarkdown.model
import com.wbrawner.simplemarkdown.utility.ErrorHandler
import com.wbrawner.simplemarkdown.utility.Utils
import java.io.*
import java.io.InputStream
import java.io.OutputStream
import java.io.Reader
/**
* This class serves as a wrapper to manage the manage the file input and output operations, as well
* as to keep track of the data itself in memory.
*/
class MarkdownFile {
var name: String? = null
var content: String? = null
private val errorHandler: ErrorHandler
class MarkdownFile(var name: String = "Untitled.md", var content: String = "") {
constructor(errorHandler: ErrorHandler, name: String, content: String) {
this.errorHandler = errorHandler
fun load(name: String, inputStream: InputStream): Boolean {
this.name = name
this.content = content
}
constructor(errorHandler: ErrorHandler) {
this.errorHandler = errorHandler
this.name = "Untitled.md"
this.content = ""
}
fun load(name: String, `in`: InputStream): Boolean {
val sb = StringBuilder()
var reader: BufferedReader? = null
try {
reader = BufferedReader(InputStreamReader(`in`))
var line: String
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n')
}
this.name = name
this.content = sb.toString()
return true
} catch (ignored: IOException) {
return false
} finally {
Utils.closeQuietly(reader)
return try {
this.content = inputStream.reader().use(Reader::readText)
true
} catch (e: Throwable) {
false
}
}
fun save(name: String, outputStream: OutputStream): Boolean {
var writer: OutputStreamWriter? = null
try {
writer = OutputStreamWriter(outputStream)
writer.write(this.content)
this.name = name
} catch (ignored: IOException) {
return false
} finally {
Utils.closeQuietly(writer)
return try {
outputStream.writer().use {
it.write(this.content)
}
true
} catch (e: Throwable) {
false
}
return true
}
}