zoukankan      html  css  js  c++  java
  • Andorid中如何读取文件

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

    提示:由于文件是打包到apk之中了所以该文件就只能进行读取的操作,不能进行写入的操作,若需要写入则需要将文件放到sdcard中进行操作

    方法一: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";
            }
        }
  • 相关阅读:
    uni-app开发经验分享九: 组件传值
    uni-app开发经验分享八: 实现微信APP支付的全过程详解
    CSS3+JS完美实现放大镜模式
    原生JS拖拽
    LeetCode 797. 所有可能的路径
    面试题 02.01. 移除重复节点
    LeetCode 139. 单词拆分
    LeetCode 1436. 旅行终点站
    LeetCode 16. 最接近的三数之和
    Hadoop 3.13在Ubuntu20.04上的单机伪分布式配置
  • 原文地址:https://www.cnblogs.com/zblwyj/p/11328563.html
Copyright © 2011-2022 走看看