目录
- 如何解决读取properties文件读取问题
 - 问题描述
 - 路径设置
 - 中文乱码
 - 读取指定properties文件
 - 设置配置属性类型
 - 配置文件
 
如何解决读取properties文件读取问题
问题描述
今天在springboot项目架构中,测试读取properties配置文件出现了两个问题:
- 路径设置
 - 中文乱码
 
路径设置
解决思路是使用org.springframework.core.io下的ClassPathResource类获取流对象,然后使用properties进行读取
中文乱码
将从ClassPathResource中获取的流对象转换为BufferReader对象
public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        ClassPathResource classPathResource = new ClassPathResource("ProducerQuickStart.properties");
        InputStream inputStream = classPathResource.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        properties.load(bufferedReader);
        Set<Object> keySets = properties.keySet();
        Iterator<Object> iterator = keySets.iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
            System.out.println("键:"+obj+"   值:"+properties.get(obj));
        }
    }
读取指定properties文件
设置配置属性类型
/**
 * 自定义配置属性类
 * @author ZH_FTP
 *
 */
@Component
//springboot 管理
@ConfigurationProperties(prefix = "validity")
//键值前缀
@PropertySource(value = {"classpath:/config/baseproperties.properties"}, encoding = "utf-8")
// 配置文件路径 解码方式
public class BaseProperties {
    private static final int INT_ZERO = 0;
    @Value("${validity.of.captcha}")
    private Integer validityOfCaptcha;//验证码有效时间
    public Integer getValidityOfCaptcha() {
        return validityOfCaptcha;
    }
    public void setValidityOfCaptcha(Integer validityOfCaptcha) {
        this.validityOfCaptcha = validityOfCaptcha;
    }
}
配置文件
在工程 /src/main/resources/config/baseproperties.properties 文件类型 配置信息 方便配置类读取
validity.of.captcha=120
读取配置文件就完成了,可以通过springboot 自动注入使用了
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
		
评论(0)