com.cntool.core.teat.PropertiesUtils Maven / Gradle / Ivy
The newest version!
package com.cntool.core.teat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @program: cntool
* @description: 配置文件工具类
* @author: ID-Tang
* @create: 2022-01-21 10:12
* @copyright: Copyright (c) [2022] [ID-tang]
* [cntool] is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
**/
public class PropertiesUtils {
/**
* properties
*/
private static Properties properties = null;
/**
* 根据key获取value值
*
* @param key 配置文件key
* @return value值
*/
public static String getValue(String key) {
if (properties == null) {
properties = loadConfProperties();
}
String value = properties.getProperty(key);
System.out.println("从配置文件读取参数: " + key + " -->> " + value);
return value;
}
/**
* 初始化propertiies
*
* @return Properties
*/
public static Properties loadConfProperties() {
Properties properties = new Properties();
InputStream in = null;
// 优先从项目路径获取连接信息
String confPath = System.getProperty("user.dir");
confPath = confPath + File.separator + "application.properties";
File file = new File(confPath);
if (file.exists()) {
System.out.println("配置文件路径---->>" + confPath);
try {
in = new FileInputStream(confPath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 未传入路径时,读取classpath路径
else {
System.out.println("项目路径[" + confPath + "]下无连接信息,从classpath路径下加载");
in = PropertiesUtils.class.getClassLoader().getResourceAsStream("application.properties");
}
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
}