首页 > 其他 > 详细

Andorid中如何读取文件

时间:2019-08-09 17:37:19      阅读:72      评论:0      收藏:0      [点我收藏+]

  由于项目中需要将一些默认配置文件打包到apk中,所以之前的存储在sdCard中的方案被推翻了,故此在网上寻找了如何读取apk中的配置文件,自己测试通过的方法有2种,在此记录一下,方便与以后遇到类似问题能更快的解决。

方法一:context.getAssets() 

  将需要读取的文件存放到/app/src/main/assets目录下,如aaa.properties文件,Properties 类是用于解析内容的

提示:可能你的项目中main的路径下没有assets这个目录,需要手动创建,要保证和java目录平级,切记不能使用res下的assets文件夹

 public  String getVaue() {
        Properties pro = null;
        InputStream is = null;
        try {
            pro = new Properties();
//            is = MainActivity.this.getResources().openRawResource(R.raw.peizhi_default);
            is = MainActivity.this.getAssets().open("aaa.properties");
            pro.load(is);
            String value = pro.getProperty("WANGLUOSHEZHI_DNS")+"";     //根据key直接获取内容
            return value;
        } catch (IOException e) {
            e.printStackTrace();
            return  "000";
        }
    }

方法二:context.getResources().openRawResource(R.raw.test); 

  将要读取的文件aaa.properties存放到/app/src/main/res/raw目录下,若raw目录不存在则手动创建,然后使用如下方式去获取

 public  String getVaue() {
        Properties pro = null;
        InputStream is = null;
        try {
            pro = new Properties();
            is = MainActivity.this.getResources().openRawResource(R.raw.aaa);
//            is = MainActivity.this.getAssets().open("aaa.properties");
            pro.load(is);
            String value = pro.getProperty("WANGLUOSHEZHI_DNS")+"";     //根据key直接获取内容
            return value;
        } catch (IOException e) {
            e.printStackTrace();
            return  "000";
        }
    }

Andorid中如何读取文件

原文:https://www.cnblogs.com/zblwyj/p/11328563.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!