Uiautomator读取properties文件

本文详细介绍如何在Android项目中创建并读取assets文件夹下的prop文件,包括使用Context和类加载器两种方法,适用于Uiautomator测试脚本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 创建assets文件夹

工程上右键New-->Folder-->Assets Folder

2. 在assets文件夹中创建prop文件

在assets文件夹中右键New-->File,输入名称xxx.prop

 3. 在prop文件中添加参数,格式为 key=Value ,如

time = 100
name = qq

4. 封装读取差数方法

方法一(通过Context):

    public String getProperties(Context c, String s) {
        String getValue = null;
        Properties properties = new Properties();
        try {
            properties.load(c.getAssets().open("***.prop"));
            getValue = properties.getProperty(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getValue;
    }

5. 在Uiautomator测试脚本中调用

getProperties(InstrumentationRegistry.getTargetContext(), "key");

注意,这里需要用到getTargetContext()而不是getContext()

getContext():  返回instrumentation对应包的Context
getTargetContext(): 返回一个目标应用程序的Context

通俗一点说明就是:
如果是使用应用apk相关的内容就用getTargetContext(), 如果是测试apk相关的就用getContext()
我们这里的prop文件是在应用路径下,所以是getTargetContext()

具体区别可以参考:https://stackoverflow.com/questions/29969545/whats-the-difference-between-gettargetcontext-and-getcontext-on-instrumentat

方法二(通过类加载器): 

public String getProperties(String s) {
        Properties prop = new Properties();

        try {
            prop.load(FileClass.class.getResourceAsStream("/assets/test.prop"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String getValue =  prop.getProperty(s);
        return  getValue;
    }

其中,FileClass为当前类。然后通过普通的调用即可读取到配置文件内容。 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值