public static Properties loadProps(String fileName) {
        Properties props = null;
        InputStream is = null;
        try {
            //注意:main/java、main/resources、test/java、test/resources这四个目录都是classpath的根目录
            //,当运行单元测试时,遵循“就近原则”,即优先从test/java、test/resources加载类或读取文件
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            if (is == null) {
                throw new FileNotFoundException(fileName + " file is not found");
            }
            props = new Properties();
            props.load(is);
        } catch (IOException e) {
            LOGGER.error("load properties file failure", e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("close input stream failure", e);
                }
            }
        }
        return props;
    }

代码中的注释是在做有关单元测试的项目中写的,附上下图好理解。如果config.properties就在resources文件夹下,fileName="config.properties";如果config.properties在config文件夹下,fileName="config/config.properties"

javaWeb加载Properties文件

 

相关文章:

  • 2022-01-16
  • 2021-11-20
  • 2021-06-21
  • 2021-06-27
  • 2022-02-18
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-18
  • 2021-12-22
  • 2021-12-18
  • 2022-12-23
  • 2022-12-23
  • 2021-07-16
相关资源
相似解决方案