AndroidでMarkdownを読み込む
- JavaでMarkdownを読み込むには
res/raw/hoge.md
にmarkdownを配置して
private String readMarkdown(@RawRes int rawId) {
final Resources resources = getResources();
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
try {
InputStream inputStream = resources.openRawResource(rawId);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String string;
while ((string = br.readLine()) != null) {
sb.append(string).append("\n");
}
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
これで読み込めます。
- Kotlinだとtry-with-resourceをuseという拡張関数で置き換えられます
private fun readMarkdown(@RawRes rawId: Int): String {
val stringBuilder = StringBuilder()
BufferedReader(InputStreamReader(resources.openRawResource(rawId))).use {
var line = it.readLine()
while (line != null) {
stringBuilder.append(line).append('\n')
line = it.readLine()
}
}
return stringBuilder.toString()
}
- ちなみにuseの中身
/**
* Executes the given [block] function on this resource and then closes it down correctly whether an exception
* is thrown or not.
*
* @param block a function to process this closable resource.
* @return the result of [block] function on this closable resource.
*/
public inline fun <T : Closeable, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
close()
} catch (closeException: Exception) {
// eat the closeException as we are already throwing the original cause
// and we don't want to mask the real exception
// TODO on Java 7 we should call
// e.addSuppressed(closeException)
// to work like try-with-resources
// http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#suppressed-exceptions
}
throw e
} finally {
if (!closed) {
close()
}
}
}
- さらにkotlinの拡張関数をうまく使うとこんなに短くなります。
private fun readMarkdown(@RawRes rawId: Int) = buildString {
resources.openRawResource(rawId)
.bufferedReader()
.useLines { it.forEach { appendln(it) } }
}
- さらにエバンジェリストたろうさんの助言により更に短くなりました。(1/21 追記)
private fun readMarkdown(@RawRes rawId: Int) =
resources.openRawResource(rawId).bufferedReader().use { it.readText() }