java 代码加载配置文件,获取里面的配置信息

1. 直接用IO流读取

File f1 = new File("C:/test/com/dj/config/system.properties"); // 使用绝对路径  
File f2 = new File("com/dj/config/system.properties"); // 使用相对路径  
InputStream is = new FileInputStream(f1);    
2. 使用ClassLoader

InputStream is1 = this.getClass().getClassLoader().getResourceAsStream("com/dj/config/system.properties"); //方法1  
InputStream is2 = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/dj/config/system.properties"); //方法2  
InputStream is3 = ClassLoader.getSystemResourceAsStream("com/dj/config/system.properties"); //方法3 

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Hashtable;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: ldj
 * Date: 2023/2/27
 * Time: 23:38
 * Description: 读取自定义配置文件properties
 */
public class ClassLoaderDemo {

    public static void main(String[] args) throws IOException {

        ClassLoader classLoader = ClassLoaderDemo.class.getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("User.properties");

        //java自带封装根据
        //Properties properties = new Properties();
        //properties.load(inputStream);
        //System.out.println(properties.getProperty("name","UTF-8"));

        Map<String, String> properties = readStream(inputStream);
        System.out.println(properties);
        System.out.println(properties.get("age"));
    }

    private static Map<String, String> readStream(InputStream inputStream) throws IOException {
        Map<String, String> hashtable = new Hashtable<>();
        if (Objects.nonNull(inputStream)) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            try {
                while (reader.ready()) {
                    String contextLine = reader.readLine();
                    if (StringUtils.isNotBlank(contextLine) && contextLine.contains("=")) {
                        String[] split = contextLine.split("=");
                        if (split.length == 2) {
                            hashtable.put(split[0], unicodeDecode(split[1]));
                        } else {
                            System.out.println("配置文件格式有误!");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                reader.close();
                inputStream.close();
            }
        }
        return hashtable;
    }

    /**
     * 中文会转成unicode,需要解码  例子(张豪:\u5F20\u8C6A)
     * '\\\' 匹配 "\"
     * 'u'单独存在
     * \p {XDigit} 匹配任何十六进制字符 {4}只有4位
     */
    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char cha;
        while (matcher.find()) {
            cha = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), cha + "");
        }
        return string;
    }

}
3. 使用ResourceBundle

ResourceBundle bundle = ResourceBundle.getBoundle("com/dj/config/system.properties");   

后续补充:

@Configuration
@Slf4j
public class PostProcessorConfig implements EnvironmentPostProcessor {

    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MutablePropertySources propertySources = environment.getPropertySources();
        this.loadProperty(propertySources);
    }

    private void loadProperty(MutablePropertySources propertySources) {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources = resolver.getResources("classpath*:sa-*.yaml");
            if (resources.length < 1) {
                return;
            }
            for (Resource resource : resources) {
                log.info("初始化系统配置:{}", resource.getFilename());
                List<PropertySource<?>> load = loader.load(resource.getFilename(), resource);
                load.forEach(propertySources::addLast);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值