java读取.properties文件

Posted by Alei Blog on November 21, 2017

场景

  • 读取.properties配置文件

代码示例

  • myconfig.properties文件路径是工程下的classes/tech/alei/boot/conf/myconfig.properties
  • 文件编码是utf-8,需要注意处理中文乱码
    package tech.alei.boot;
      
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Properties;
      
    public class PropertiesUtil {
      
        public static String getValue(String key){
            Properties prop = new Properties();
            try {
                InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("tech/alei/boot/conf/myconfig.properties");
                prop.load(new InputStreamReader(in, "UTF-8"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return prop.getProperty(key);
        }
    }