zoukankan      html  css  js  c++  java
  • 如何读取配置文件

    在进行自动化测试时,时常会设置一些共通性的配置,比如你的测试用例放在那里,是否要初始化,使用哪个浏览器,报告要以哪种方式展示等等

    一般有三种方式可以实现这个功能,我这里只说我认为不错并且使用的一种方式。

    ------------------------------------------------------我是举例子开始的线---------------------------------

    1.创建一个配置文件config.properties,里面写清楚要配置的项:TestData=c:/TestData.xls

    2.创建一个类,把TestData设计成key

    public interface CommonKeys {

    public static final String CommonKey = "config.properties";

    public static final String TestDataKey = "TestData";

    }

    3.创建一个类,通过key能读取value

    使用Properties关键字

    1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

    2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

    3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

    4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

    5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。

    public class CommonUtil {

    public String getconfigByKey(String key){
    Properties properties =new Properties();
    try {
    InputStreamReader in=new InputStreamReader(ClassLoader.getSystemClassLoader().getResourceAsStream(CommonKeys.CommonKey),"UTF-8");
    properties.load(in);

    //也可以写成:properties.load(new InputStreamReader(ClassLoader.getSystemClassLoader().getResourceAsStream(CommonKeys.CommonKey),"UTF-8"));


    String value = properties.getProperty(key);
    System.out.println(key + " = " + value);
    return value;
    }catch (IOException e) {
    e.printStackTrace();
    return null;
    }
    }

    }

     

    扩展思路:配置文件里添加一个新的配置项→在CommonKeys 中设置新的“key” →CommonUtil 就可以通过新的key读取配置项的“value”

    还有一种方法是在本地中写一个excel表作为配置项,通过管理excel表来控制配置项,我觉得没有这种方便

  • 相关阅读:
    vmware虚拟机安装centos,配置PHP、mysql
    Java初学者不得不知的概念,JDK,JRE,JVM的区别?(转)
    char a[] = "hello world1"和char *p = "hello world2";的区别(转)
    关于二维数组传参做形参(转)
    最长连续字母序列的长度(阿里2015在线研发工程师笔试题)
    两个线程并发执行以下代码,假设a是全局变量,那么以下输出______是不可能的?
    软件工程
    面向对象基础
    eclipse
    设计模式(java)--状态模式
  • 原文地址:https://www.cnblogs.com/tangtongxue/p/7262741.html
Copyright © 2011-2022 走看看