public static void main(String[] args) {
/* path中不以'/'开头表示该路径是相对路径,相对于当前类所在的目录 */
InputStream is = PropertiesUtil.class.getResourceAsStream("cfg/jdbc.properties");
// 同 InputStream is = this.getClass().getResourceAsStream("cfg/jdbc.properties"); --this.getClass()不能在static方法中使用
/* path中以'/'开头表示该路径是绝对路径,相对于classpath的绝对路径 */
InputStream is2 = PropertiesUtil.class.getResourceAsStream("/com/gr/cfg/jdbc.properties");
// 同 InputStream is2 = this.getClass().getResourceAsStream("/com/gr/cfg/jdbc.properties"); --this.getClass()不能在static方法中使用
// 同 InputStream is2 = Thread.currentThread().getClass().getResourceAsStream("/com/gr/cfg/jdbc.properties");
/* 使用getClassLoader()表示该路径是相对于classpath目录的相对路径*/
InputStream is3 = PropertiesUtil.class.getClassLoader().getResourceAsStream("com/gr/cfg/jdbc.properties");
// 同 InputStream is3 = this.getClass().getClassLoader().getResourceAsStream("com/gr/cfg/jdbc.properties"); --this.getClass()不能在static方法中使用
// 同 InputStream is3 = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/gr/cfg/jdbc.properties");
//这3种方式读取的文件是在项目的resource目录下。使用第三种方式使用相对路径会简单些
}
java读取项目资源文件
最新推荐文章于 2022-11-23 11:31:02 发布