Read Assets file as string

前端 未结 4 1082
耶瑟儿~
耶瑟儿~ 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:26

    hi this is in my opinion the cleanest approach:

      public static String loadTextFromAssets(Context context, String assetsPath, Charset charset) throws IOException {
            InputStream is = context.getResources().getAssets().open(assetsPath);
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (int length = is.read(buffer); length != -1; length = is.read(buffer)) {
                baos.write(buffer, 0, length);
            }
            is.close();
            baos.close();
            return charset == null ? new String(baos.toByteArray()) : new String(baos.toByteArray(), charset);
        }
    

    because readers could get trouble with line breaks.

提交回复
热议问题