Java Java 对 properties 文件操作 (ResourceBundle 类和 Properties 类)

伍个一 for 杭州软件测试圈 · December 18, 2020 · 1429 hits

1. 使用场景

properties 文件多为配置信息,日常操作很频繁,例如测试框架中的接口配置文件,如下

test.url=http://localhost:8888

#登陆接口uri
#login.uri=/v1/login
login.uri=/login
#更新用户信息接口uri
updateUserInfo.uri=/v1/updateUserInfo

#获取用户列表接口uri
getUserList.uri=/v1/getUserInfo

#获取用户信息接口uri
getUserInfo.uri=/v1/getUserInfo

#添加用户接口uri
addUser.uri=/v1/addUser

那么,在写接口用例的时候,怎么获取到这些对应的测试数据呢?
示例

2. 第一种方法:ResourceBundle 类

//第一种  ResourceBundle类
//1. 声明ResourceBundle并获取文件
ResourceBundle bundle = ResourceBundle.getBundle("application", Locale.CHINA);
//2. 获取值
String apiValue = bundle.getString("login.uri");

System.out.println("ResourceBundle类方式提取数据:" + apiValue);

3. 第二种方法:Properties 类

//1. 文件路径
       String dataPath = "src/main/resources/application.properties";
       try {
           //2.获取输入流
           InputStream inputStream = new BufferedInputStream(new FileInputStream(new File(dataPath)));
           //3. 声明Properties类
           Properties properties = new Properties();
           //4. 从字节输入流中读取键值对。
           properties.load(inputStream);
           //5. 获取值
           String string = properties.getProperty("login.uri");

           System.out.println("Properties类提取数据:" + string);
       } catch (IOException e) {
           System.out.println("properties文件路径书写错误,请检查!");
       }

控制台

4. ResourceBundle 类和 Properties 类的差异

ResourceBundle 类通常是用于针对不同的语言来使用的属性文件。

而如果你的应用程序中的属性文件只是一些配置,并不是针对多国语言的目的。那么使用 Properties 类就可以了。

通常可以把这些属性文件放在某个 jar 文件中。然后,通过调用 class 的 getResourceAsStream 方法,来获得该属性文件的流对象,再用 Properties 类的 load 方法来装载。

No Reply at the moment.
需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up