You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
SDMS/src/com/itheima/util/PropertiesUtil.java

65 lines
3.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.itheima.util; // 定义该类属于com.itheima.util包
/**
* @program: dormitorySystem
* @description: 属性工具类,用于加载和获取配置文件中的属性
* @author: Joyrocky
* @create: 2019-04-28 23:10
**/
import org.apache.commons.lang3.StringUtils; // 导入Apache Commons Lang库中的StringUtils工具类用于处理字符串
import org.slf4j.Logger; // 导入SLF4J日志库中的Logger类
import org.slf4j.LoggerFactory; // 导入SLF4J日志库中的LoggerFactory类
import java.io.IOException; // 导入IOException用于处理IO异常
import java.io.InputStreamReader; // 导入InputStreamReader用于将字节流转换为字符流
import java.util.Properties; // 导入Properties类用于读取和操作属性文件
public class PropertiesUtil {
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class); // 创建一个Logger对象用于记录日志
private static Properties props; // 声明一个静态的Properties对象用于存储加载的属性文件内容
// 静态代码块,用于加载配置文件
static {
String fileName = "mmall.properties"; // 设置要加载的配置文件名称
props = new Properties(); // 实例化Properties对象
try {
// 使用InputStreamReader将配置文件位于类路径下加载到Properties对象中并指定字符集为UTF-8
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName), "UTF-8"));
} catch (IOException e) { // 捕获IO异常
logger.error("配置文件读取异常", e); // 记录读取配置文件异常的日志
}
}
/**
* 获取配置文件中指定键的值
*
* @param key 要获取的属性键
* @return 配置文件中指定键的值如果值为空或未找到则返回null
*/
public static String getProperty(String key){
String value = props.getProperty(key.trim()); // 获取配置文件中指定键对应的值,去除键值的前后空格
if(StringUtils.isBlank(value)){ // 判断获取到的值是否为空或仅包含空白字符
return null; // 如果为空则返回null
}
return value.trim(); // 如果值不为空,则去除值的前后空格并返回
}
/**
* 获取配置文件中指定键的值,如果值为空,则返回默认值
*
* @param key 要获取的属性键
* @param defaultValue 如果配置文件中没有指定键的值,则返回该默认值
* @return 配置文件中指定键的值,如果值为空或未找到则返回默认值
*/
public static String getProperty(String key, String defaultValue){
String value = props.getProperty(key.trim()); // 获取配置文件中指定键对应的值,去除键值的前后空格
if(StringUtils.isBlank(value)){ // 判断获取到的值是否为空或仅包含空白字符
value = defaultValue; // 如果值为空,则使用默认值
}
return value.trim(); // 返回最终的值,去除前后空格
}
}