读取xx.properties文件里面的属性

本文详细介绍了如何使用Java读取Properties文件的过程,包括通过线程上下文类加载器获取文件流,利用Properties类加载流并解析键值对,以及如何通过getProperty方法获取属性值。

对properties文件读取里面的属性
1、首先通过当前线程的上下文类加载去将properties文件的路径资源转化为InputStream

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("dqms.properties");

2、然后通过Properties类去加载这个inputStream就读取了properties文件

private static Properties dataProps=new Properties();
dataProps.load(inputStream);

3、想要获取里面的属性,只需要调用Properties类的getProperty(name)就可获取name的值,String类型。

dataProps.getProperty(name)

上面基本就能获取值,有需要更加了解的看下面源码:

1、对getResourceAsStream(String xx)进行分析,将属性文件读入内存的InputStream流中。

public InputStream getResourceAsStream(String name) {
        URL url = getResource(name);
        try {
            return url != null ? url.openStream() : null;
        } catch (IOException e) {
            return null;
        }
    }
/*获取资源的路径,首先从自身的类加载获取资源,如果没有知道就去根目录去找,如果还是空则为null*/
private final ClassLoader parent;
public URL getResource(String name) {
        URL url;
        if (parent != null) {
            url = parent.getResource(name);    //本项目资源路径下去找
        } else {
            url = getBootstrapResource(name);//JDK\jre\lib路径下去找
        }
        if (url == null) {
            url = findResource(name);    //null
        }
        return url;
    }
//英文解释说该方法最好被重写
protected URL findResource(String name) {
        return null;
    }
/*url打开这个链接并返回InputStream*/
public final InputStream openStream() throws java.io.IOException {
        return openConnection().getInputStream();
    }

2、Properties类对Input进行load加载转化为properties对象。

通过源码可以看到对properties的格式要求有五种:(1)冒号:(2)等号=(3)空格“ ”(4)制表符\t(5)换页符\f

//synchronized进行同步,从InputStream里面读取properties集合(键值对),读取完成后,该InputStream还是开着的,没有关闭
public synchronized void load(InputStream inStream) throws IOException {
        load0(new LineReader(inStream));
    }
//看看源码发现他把每行的键值对,存到HashTable的map上
 private void load0 (LineReader lr) throws IOException {
        char[] convtBuf = new char[1024];
        int limit;    //每一行的最后字符位置
        int keyLen;    //每一行的key的长度
        int valueStart;//每一行的value的开头字符位置
        char c;
        boolean hasSep;
        boolean precedingBackslash;
        //lr.readLine()会每行每行读取,》=0说明最后还有值
        while ((limit = lr.readLine()) >= 0) {
            c = 0;
            keyLen = 0;    //每一行keyLen都会从每行的头开始,像指针,到一定位置
            valueStart = limit;
            hasSep = false;

            //System.out.println("line=<" + new String(lineBuf, 0, limit) + ">");
            precedingBackslash = false;
            //循环key部分
            while (keyLen < limit) {
                c = lr.lineBuf[keyLen];    //在每一行的位置上的字符,从0开始
                //检查=或:这两种格式
                if ((c == '=' ||  c == ':') && !precedingBackslash) {
                    valueStart = keyLen + 1;
                    hasSep = true;
                    break;
                } //检查为空、制表符、换页符
                else if ((c == ' ' || c == '\t' ||  c == '\f') && !precedingBackslash) {
                    valueStart = keyLen + 1;
                    break;
                }
                if (c == '\\') {
                    precedingBackslash = !precedingBackslash;
                } else {
                    precedingBackslash = false;
                }
                keyLen++;
            }
            //循环value部分
            while (valueStart < limit) {
                c = lr.lineBuf[valueStart];//在每一行的位置上的字符,从valueStart开始
                if (c != ' ' && c != '\t' &&  c != '\f') {
                    if (!hasSep && (c == '=' ||  c == ':')) {
                        hasSep = true;
                    } else {
                        break;
                    }
                }
                valueStart++;//遇到空格,制表符,换页符隔过去,value开头的位置直接++;
            }
            String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
            String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
            put(key, value);    //因为Properties继承了HashTable,所以这个put方法是HashTable的方法
        }
    }

3、getProperties("xx")实质是:map的get();

//因为继承了HashTable,调用super.get(),是调用map.get()
public String getProperty(String key) {
        Object oval = super.get(key);
        String sval = (oval instanceof String) ? (String)oval : null;
        return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
    }


    

C:\dev\jdk1.8.0_332\bin\java.exe -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:59411,suspend=y,server=n -Dusf.service.environment=dev_ywx1446235 -Dspring.profiles.active=dev -Dapic_account=com.huawei.tgmes.tmas -Dsoa_innernet_domain=http://oauth2-beta.huawei.com -agentpath:C:\Users\yWX1446235\AppData\Local\Temp\idea_libasyncProfiler_dll_temp_folder8\libasyncProfiler.dll=version,jfr,event=wall,interval=10ms,cstack=no,file=C:\Users\yWX1446235\IdeaSnapshots\TmasApplication_2025_08_27_175500.jfr,dbghelppath=C:\Users\yWX1446235\AppData\Local\Temp\idea_dbghelp_dll_temp_folder\dbghelp.dll,log=C:\Users\yWX1446235\AppData\Local\Temp\TmasApplication_2025_08_27_175500.jfr.log.txt,logLevel=DEBUG -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-Dmanagement.endpoints.jmx.exposure.include=*" -javaagent:C:\Users\yWX1446235\AppData\Local\JetBrains\IntelliJIdea2024.3\captureAgent\debugger-agent.jar -Dkotlinx.coroutines.debug.enable.creation.stack.trace=false -Ddebugger.agent.enable.coroutines=true -Dkotlinx.coroutines.debug.enable.flows.stack.trace=true -Dkotlinx.coroutines.debug.enable.mutable.state.flows.stack.trace=true -Dfile.encoding=UTF-8 -classpath C:\Users\yWX1446235\AppData\Local\Temp\classpath1923282718.jar com.huawei.it.tgmes.TmasApplication Connected to the target VM, address: '127.0.0.1:59411', transport: 'socket' 2025-08-27 17:55:02 [main] INFO TmasApplication:49 - DFS: setSystemProperty, key = [hwenvironment] not exists, set it with vaule = [uat] 2025-08-27 17:55:03 [main] INFO TmasApplication:49 - DFS: setSystemProperty, key = [idaas_match_domain] not exists, set it with vaule = [false] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-application-dev:default.application-dev.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-application:default.application.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-hisapplication-dev:default.hisapplication-dev.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-hisapplication:default.hisapplication.properties] 2025-08-27 17:55:03 [main] INFO MesSecretPropertiesDecrypter:41 - Mes Secret Properties Decrypt is Disabled 2025-08-27 17:55:03 [main] INFO BootstrapEnvironmentPostProcessor:101 - com.huawei.his.jalor.config.BootstrapEnvironmentPostProcessor works! 2025-08-27 17:55:03 [main] INFO BootstrapEnvironmentPostProcessor:106 - load [application-global.properties] jalor default properties. 2025-08-27 17:55:03 [main] WARN BootstrapEnvironmentPostProcessor:111 - load [application-global.properties] jalor default properties error: class path resource [application-global.properties] cannot be opened because it does not exist 2025-08-27 17:55:03 [main] INFO BootstrapEnvironmentPostProcessor:106 - load [common.application.properties] jalor default properties. 2025-08-27 17:55:03 [main] WARN BootstrapEnvironmentPostProcessor:111 - load [common.application.properties] jalor default properties error: class path resource [common.application.properties] cannot be opened because it does not exist 2025-08-27 17:55:03 [main] INFO BootstrapEnvironmentPostProcessor:106 - load [jalor.application.properties] jalor default properties. 2025-08-27 17:55:03 [main] INFO BootstrapEnvironmentPostProcessor:123 - com.huawei.his.jalor.config.pcloud.PcloudConfigurationLoader named pcloud-environment configuration disabled! 2025-08-27 17:55:03 [main] INFO BootstrapEnvironmentPostProcessor:123 - com.huawei.his.jalor.https.decrypt*****#*#*****ocessor named TrustStoreDecryptProcessor configuration disabled! 2025-08-27 17:55:03 [main] INFO BootstrapEnvironmentPostProcessor:123 - com.huawei.his.jalor.config.hae.HaeConfigurationLoader named hae.config configuration disabled! 2025-08-27 17:55:03 [main] INFO DiffApplicationConfigurationLoader:43 - Read the config 'jalor.config.diff' is : null 2025-08-27 17:55:03 [main] INFO BootstrapEnvironmentPostProcessor:123 - com.huawei.his.jalor.config.DiffApplicationConfigurationLoader named application-<diff>.properties configuration disabled! 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-executeInBatches:default.executeInBatches.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-myBatisLogPlugin:default.myBatisLogPlugin.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-bootcheck:default.bootcheck.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-logScheduler:default.logScheduler.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-traceLog:default.traceLog.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-datasource:default.datasource.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-lookupContext:default.lookupContext.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-ischeduler:default.ischeduler.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-hisbootcheck-dev:default.hisbootcheck-dev.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-hisbootcheck:default.hisbootcheck.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-idaas:default.idaas.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-dynamicProperties:default.dynamicProperties.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-idata:default.idata.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-penetrateLog:default.penetrateLog.properties] 2025-08-27 17:55:03 [main] INFO PropertiesUtils:115 - Property loaded [default-processlog:default.processlog.properties] 2025-08-27 17:55:03 [main] INFO MesSecretPropertiesDecrypter:41 - Mes Secret Properties Decrypt is Disabled 2025-08-27 17:55:03 [main] INFO MesBootReporter:132 - ********************************************************************************************************************************************************************************************************************************************************** 2025-08-27 17:55:03 [main] INFO MesBootReporter:133 - * 2025-08-27 17:55:03 [main] INFO MesBootReporter:144 - * MESService Boot Report 2025-08-27 17:55:03 [main] INFO MesBootReporter:144 - * 17:55:03.197 : Spring Boot: 应用开始启动 2025-08-27 17:55:03 [main] INFO MesBootReporter:144 - * 17:55:03.942 : Spring Boot: 应用启动失败 2025-08-27 17:55:03 [main] INFO MesBootReporter:144 - * 17:55:03.946 : java.lang.IllegalArgumentException: Could not resolve placeholder 'j2c.sgovToken*****#*#*****password*****#*#*****ovToken*****#*#*****password*****#*#*****ringframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180)[N][N][N]at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)[N][N][N]at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239)[N][N][N]at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210)[N][N][N]at org.springframework.core.env.AbstractPropertyResolver.resolveNestedPlaceholders(AbstractPropertyResolver.java:230)[N][N][N]at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:79)[N][N][N]at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:60)[N][N][N]at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:594)[N][N][N]at com.huawei.it.mes.utils.dfx.monitor.DfxMesApplication$Initializer.postProcessEnvironment(DfxMesApplication.java:49)[N][N][N]at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEnvironmentPreparedEvent(EnvironmentPostProcessorApplicationListener.java:102)[N][N][N]at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEvent(EnvironmentPostProcessorApplicationListener.java:87)[N][N][N]at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:178)[N][N][N]at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:171)[N][N][N]at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:145)... 2025-08-27 17:55:03 [main] INFO MesBootReporter:144 - * Failed Spend:778 ms 2025-08-27 17:55:03 [main] INFO MesBootReporter:148 - * 2025-08-27 17:55:03 [main] INFO MesBootReporter:149 - ********************************************************************************************************************************************************************************************************************************************************** 2025-08-27 17:55:03 [main] WARN MESPropertiesPrinterOnFailed:41 - Application start failed to early to print properties 2025-08-27 17:55:03 [main] ERROR SpringApplication:818 - Application run failed java.lang.IllegalArgumentException: Could not resolve placeholder 'j2c.sgovToken*****#*#*****password*****#*#*****ovToken*****#*#*****password*****#*#***** at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180) ~[spring-core-5.3.39-h2.jar:5.3.39-h2] at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-5.3.39-h2.jar:5.3.39-h2] at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-5.3.39-h2.jar:5.3.39-h2] at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-5.3.39-h2.jar:5.3.39-h2] at org.springframework.core.env.AbstractPropertyResolver.resolveNestedPlaceholders(AbstractPropertyResolver.java:230) ~[spring-core-5.3.39-h2.jar:5.3.39-h2] at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:79) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertyResolver.getProperty(ConfigurationPropertySourcesPropertyResolver.java:60) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:594) ~[spring-core-5.3.39-h2.jar:5.3.39-h2] at com.huawei.it.mes.utils.dfx.monitor.DfxMesApplication$Initializer.postProcessEnvironment(DfxMesApplication.java:49) ~[messervice-dfx-8.3.4.jar:?] at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEnvironmentPreparedEvent(EnvironmentPostProcessorApplicationListener.java:102) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEvent(EnvironmentPostProcessorApplicationListener.java:87) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:178) ~[spring-context-5.3.39-h2.jar:5.3.39-h2] at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:171) ~[spring-context-5.3.39-h2.jar:5.3.39-h2] at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:145) ~[spring-context-5.3.39-h2.jar:5.3.39-h2] at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:133) ~[spring-context-5.3.39-h2.jar:5.3.39-h2] at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:85) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:66) ~[spring-boot-2.7.18.jar:2.7.18] at java.util.ArrayList.forEach(ArrayList.java:1259) ~[?:1.8.0_332] at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:120) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:114) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:65) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:344) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300) ~[spring-boot-2.7.18.jar:2.7.18] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1289) ~[spring-boot-2.7.18.jar:2.7.18] at com.huawei.it.tgmes.TmasApplication.main(TmasApplication.java:40) ~[classes/:?] Disconnected from the target VM, address: '127.0.0.1:59411', transport: 'socket' Process finished with exit code 1
最新发布
08-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值