java读取properties配置文件

Posted lf_victor17919

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java读取properties配置文件相关的知识,希望对你有一定的参考价值。

目录结构

 

package com.wish.config;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * @Author: lfyu
 * @DateTime: 2020-06-15 10:37
 * @ProjectName: loginVerify
 * @PackageName: com.wish.config
 * @ClassName: ReadConfig
 * @Description:
 **/
public class ReadConfig {

    public static Map<String,String> map = new HashMap<>();
/*    public static Map<String,Object> read(){
        Map<String,Object> map = new HashMap<>();
        Properties properties = new Properties();
        try {
            properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
            String port = properties.getProperty("redis.port");
            String host = properties.getProperty("redis.host");
            String timeout = properties.getProperty("redis.timeout");
            String use = properties.getProperty("loginFilter.use");
            map.put("port", port);
            map.put("host", host);
            map.put("timeout", timeout);
            map.put("use", use);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }*/

    public static Map<String,String> read(){
        Properties properties = new Properties();

        try {
            InputStream in = ReadConfig.class.getClassLoader().getResourceAsStream("config.properties");
            properties.load(in);
            Iterator<String> iterator = properties.stringPropertyNames().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = properties.getProperty(key);
                map.put(key,value);
//                System.out.println("key = " + key + ",value = " +value);
            }
            return map;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

config.properties文件内容

 

 

  

执行结果

 

以上是关于java读取properties配置文件的主要内容,如果未能解决你的问题,请参考以下文章

java读取properties配置文件路径问题

Java读取properties配置文件

java程序读取properties配置文件出现中文乱码

Java 读取application.properties配置文件中配置

Java读取和写入配置文件Properties

Java读取和写入配置文件Properties