美文网首页
工具类:读取Assets文件

工具类:读取Assets文件

作者: 楷桐 | 来源:发表于2018-02-28 16:51 被阅读130次
    public final class AssetsUtils {
    
        private AssetsUtils() {
            throw new UnsupportedOperationException("u can't instantiate me...");
        }
    
        /**
         * 从文件中获取字符串
         *
         * @param fileName
         * @param context
         * @return
         */
        public static String getString(String fileName, Context context) {
            StringBuilder stringBuilder = new StringBuilder();
            try {
                AssetManager assetManager = context.getAssets();
                BufferedReader bf = new BufferedReader(new InputStreamReader(
                        assetManager.open(fileName)));
                String line;
                while ((line = bf.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return stringBuilder.toString();
        }
    
        /**
         * 根据字符串返回实体类
         *
         * @param fileName
         * @param context
         * @param tClass
         * @param <T> 实体类
         * @return
         */
        public static <T>  T getJsonObject(String fileName, Context context, Class<T> tClass) {
            String jsonStr = getString(fileName, context);
            Gson gson = new Gson();
            return gson.fromJson(jsonStr, tClass);
        }
    }
    

    相关文章

      网友评论

          本文标题:工具类:读取Assets文件

          本文链接:https://www.haomeiwen.com/subject/nilixftx.html