Read Assets file as string

前端 未结 4 1089
耶瑟儿~
耶瑟儿~ 2020-12-01 08:52

I would like to read the content of a file located in the Assets as a String. For example, a text document located in src/main/assets/

Original

4条回答
  •  我在风中等你
    2020-12-01 09:20

    getAssets().open() will return an InputStream. Read from that using standard Java I/O:

    Java:

    StringBuilder sb = new StringBuilder();
    InputStream is = getAssets().open("book/contents.json");
    BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8 ));
    String str;
    while ((str = br.readLine()) != null) {
        sb.append(str);
    }
    br.close();
    

    Kotlin:

    val str = assets.open("book/contents.json").bufferedReader().use { it.readText() }
    

提交回复
热议问题