LoginSignup
13
9

More than 5 years have passed since last update.

Androidでmarkdown(raw)を読み込む [Java / Kotlin]

Last updated at Posted at 2016-01-20

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() }
13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9