Read Assets file as string

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

    There is a little bug CommonsWare's code - newline characters are discarded and not added to the string. Here is some fixed code ready for copy+paste:

    private String loadAssetTextAsString(Context context, String name) {
            BufferedReader in = null;
            try {
                StringBuilder buf = new StringBuilder();
                InputStream is = context.getAssets().open(name);
                in = new BufferedReader(new InputStreamReader(is));
    
                String str;
                boolean isFirst = true;
                while ( (str = in.readLine()) != null ) {
                    if (isFirst)
                        isFirst = false;
                    else
                        buf.append('\n');
                    buf.append(str);
                }
                return buf.toString();
            } catch (IOException e) {
                Log.e(TAG, "Error opening asset " + name);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        Log.e(TAG, "Error closing asset " + name);
                    }
                }
            }
    
            return null;
        }
    

提交回复
热议问题