美文网首页工作生活
Resource properties文件加载

Resource properties文件加载

作者: 大黑跟小白的日常 | 来源:发表于2019-07-04 10:08 被阅读0次

    说明

    1、获取属性文件项目路径;
    2、加载文件到读入流;

    is = Thread.currentThread().getContextClassLoader().getResourceAsStream(propsPath);
    

    3、转换成Properties对象;

    Properties props = new Properties();
    props.load(is);
    

    4、获取对象中加载的属性值;

    props.getProperty(key);
    

    具体代码如下

    package props;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    import org.apache.commons.lang.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    public class PropsReadTest {
        private static final Logger logger = LoggerFactory
                .getLogger(PropsReadTest.class);
        public static void main(String[] args) {
            Properties props = loadProps("./test.properties");
            logger.info(getString(props, "server.port"));
            logger.info(getString(props, "name"));
            logger.info(getNumber(props, "age")+"");
        }
        public static Properties loadProps(String propsPath) {
            Properties props = new Properties();
            InputStream is = null;
            try {
                if (StringUtils.isEmpty(propsPath)) {
                    throw new IllegalArgumentException();
                }
                String suffix = ".properties";
                if (propsPath.lastIndexOf(suffix) == -1) {
                    propsPath += suffix;
                }
                is = Thread.currentThread().getContextClassLoader()
                        .getResourceAsStream(propsPath);
                if (is != null) {
                    props.load(is);
                }
            } catch (Exception e) {
                logger.error("加载属性文件出错!", e);
                throw new RuntimeException(e);
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    logger.error("释放资源出错!", e);
                }
            }
            return props;
        }
        public static String getString(Properties props, String key) {
            String value = "";
            if (props.containsKey(key)) {
                value = props.getProperty(key);
            }
            return value;
        }
        public static int getNumber(Properties props, String key) {
            int value = 0;
            if (props.containsKey(key)) {
                value = Integer.valueOf(props.getProperty(key));
            }
            return value;
        }
    }
    

    文件位置

    image.png

    相关文章

      网友评论

        本文标题:Resource properties文件加载

        本文链接:https://www.haomeiwen.com/subject/cfflhctx.html