JAVA--读取配置文件中的参数

 配置文件(db.properties)位于src/main/resources/resource中且中内容如下:

jdbc.username=sa
jdbc.password=123456

获取配置文件中的参数值有方法如下:
方法1: 

public class ReadConfigurationClass {
    public static Map readConfiguration(String path) throws Exception {
        ClassLoader classLoader = ReadConfigurationClass.class.getClassLoader();
        URL resource = classLoader.getResource(path);
        String newPath = resource.getPath();

        Properties properties = new Properties();
        //可以用两种不同的流来加载配置文件
        properties.load(new BufferedReader(new FileReader(newPath)));
//        properties.load(ReadConfigurationClass.class.getResourceAsStream(path));

        //也可以指定键名来获取值
        //String name = properties.getProperty("name");
        Set> entrySet = properties.entrySet();
        Map resultMap = new HashMap<>();
        for (Map.Entry entry : entrySet) {
            resultMap.put(entry.getKey(), entry.getValue());
            System.out.println(entry.getKey()+" -- "+entry.getValue());
        }
        return resultMap;
    }
}

调用时传入配置文件的路径,如:

Map map= ReadConfigurationClass.readConfiguration("resource/db.properties");
String username= resultMap.get("jdbc.username").toString();
String passWord= resultMap.get("jdbc.password").toString();

方法2:

Properties prop = PropertiesLoaderUtils.loadProperties(new ClassPathResource("resource/sys.properties"));
String userName = prop.getProperty("jdbc.userName");
String password = prop.getProperty("jdbc.password");

即可取得参数"sa"和"123456"。

 

 

你可能感兴趣的:(JAVA)