一、介绍
此处介绍java中两种常用的解析properties方法,两种方法分别为:
-
ClassLoder方法
-
ResourceBundle方法
比较:
- 两种方法均引用自 java.util;
- 如果在文件在根目录则只需写文件名,如果不在根目录则需要带路径;
- 区别为ClassLoder方法需写文件后缀名,ResourceBundle方法无需写文件后缀名,
二、代码演示
放在路径下的配置文件:test.properties
personname=wangxiaoer
pass=thisismytest
放在src根目录下的配置文件:srctest.properties
personname=wangxiaoer_src
pass=thisismytest_src
测试类方法(ClassLoder方法);此处使用静态块初始化类的静态变量,将配置文件的变量赋值给变量。
package com.propertiesget;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;
public class PropertiesTest {
public static String personname;
public static String pass;
public static String personname_src;
public static String pass_src;
//ClassLoder方法
static {
try{
Properties properties = new Properties();
Properties properties_src = new Properties();
//如果在文件在根目录则只需写文件名,如果不在根目录则需要带路径
InputStream in = PropertiesTest.class.getClassLoader().getResourceAsStream("com/config/test.properties");
InputStream insrc = PropertiesTest.class.getClassLoader().getResourceAsStream("srctest.properties");
properties.load(in);
properties_src.load(insrc);
personname = properties.getProperty("personname");
pass =properties.getProperty("pass");
personname_src = properties_src.getProperty("personname");
pass_src =properties_src.getProperty("pass");
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(PropertiesTest.personname);
System.out.println(PropertiesTest.pass);
System.out.println(PropertiesTest.personname_src);
System.out.println(PropertiesTest.pass_src);
}
}
测试类方法(ResourceBundle方法)
package com.propertiesget;
import java.io.InputStream;
import java.util.Properties;
import java.util.ResourceBundle;
/**
* @auth yangwl
* @time 2022/12/16
*/
public class PropertiesTest {
public static String personname;
public static String pass;
public static String personname_src;
public static String pass_src;
//ResourceBundle 读取
static{
//如果在文件在根目录则只需写文件名,如果不在根目录则需要带路径,此方式文件不用带后缀.properties
ResourceBundle resourceBundle =ResourceBundle.getBundle("com/config/test");
ResourceBundle resourceBundle_src =ResourceBundle.getBundle("srctest");
personname = resourceBundle.getString("personname");
pass =resourceBundle.getString("pass");
personname_src = resourceBundle_src.getString("personname");
pass_src =resourceBundle_src.getString("pass");
}
public static void main(String[] args) {
System.out.println(PropertiesTest.personname);
System.out.println(PropertiesTest.pass);
System.out.println(PropertiesTest.personname_src);
System.out.println(PropertiesTest.pass_src);
}
}
附:项目结构: