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"