您的位置:首页 > 编程语言 > Java开发

java读取项目资源文件

2017-11-22 10:02 330 查看
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目录下。使用第三种方式使用相对路径会简单些
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: