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 package com.wbrawner.simplemarkdown.model
import com.wbrawner.simplemarkdown.utility.ErrorHandler import java.io.InputStream
import com.wbrawner.simplemarkdown.utility.Utils import java.io.OutputStream
import java.io.* import java.io.Reader
/** /**
* This class serves as a wrapper to manage the manage the file input and output operations, as well * 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. * as to keep track of the data itself in memory.
*/ */
class MarkdownFile { class MarkdownFile(var name: String = "Untitled.md", var content: String = "") {
var name: String? = null
var content: String? = null
private val errorHandler: ErrorHandler
constructor(errorHandler: ErrorHandler, name: String, content: String) { fun load(name: String, inputStream: InputStream): Boolean {
this.errorHandler = errorHandler
this.name = name this.name = name
this.content = content return try {
} this.content = inputStream.reader().use(Reader::readText)
true
} catch (e: Throwable) {
constructor(errorHandler: ErrorHandler) { false
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)
} }
} }
fun save(name: String, outputStream: OutputStream): Boolean { fun save(name: String, outputStream: OutputStream): Boolean {
var writer: OutputStreamWriter? = null this.name = name
try { return try {
writer = OutputStreamWriter(outputStream) outputStream.writer().use {
writer.write(this.content) it.write(this.content)
this.name = name }
} catch (ignored: IOException) { true
return false } catch (e: Throwable) {
} finally { false
Utils.closeQuietly(writer)
} }
return true
} }
} }