读取Properties文件时应注意的路径问题
-
InputStream in = this.getClass().getResourceAsStream("资源名称");
注意:
-
这种方式要求 Properties资源文件必须与当前类文件在同一个包下(同文件夹下) ,如果不在则会报空指针异常,如果不在同一个包(文件夹)下可以使用,如果方式:
InputStream in = this.getClass().getResourceAsStream("/config.properties");
或
InputStream in = PropertiesUtil.class.getResourceAsStream("/resources/config.properties");
-
获取获取当前类所在的包路径:
System.getProperty("user.dir");
-
-
使用Class.getClassLoader()的getResourceAsStream()读取Properties文件(资源文件)的路径问题:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/resources/config.properties");
-
使用getClassLoader()获取的是classpath路径;
-
虽然也可以使用 Object.class .getClassLoader().getResourceAsStream("/resources/config.properties") 来获取资源文件,但是 如果在Web项目中的话,会得到一个null值 ,所以保险起见, 就是这个类的本身名字来直接获取Class对象 ,如果我这个类为PropertiesUtil.java,可以使用如下方式获取:PropertiesUtil.class .getClassLoader().getResourceAsStream("/resources/config.properties");
-