getResourceAsStream读取文件

首先看看项目目录结构java

一、利用Class.getResourceAsStream(String path)spa

    path 不以’/'开头时默认是今后类所在的包下取资源,以’/'开头则是从ClassPath根下获取。其只是经过path构造一个绝对路径,最终仍是由ClassLoader获取资源。code

  • 当前目录(相对于class)资源

//调用与A.java对应的A.properties
InputStream is = A.class.getResourceAsStream("A.properties")
Properties properties = new Properties();
properties.load(is);
String name = properties.getProperty("name");

//注意:A.properties必定得在与resources目录下,且与A.java具备相同的目录结构
  • classpath路径(相对于classpath,,“/”)get

//调用与A.java对应的A.properties
InputStream is = A.class.getResourceAsStream("/package1/A.properties")
Properties properties = new Properties();
properties.load(is);
String name = properties.getProperty("name");

//注意:A.properties必定得在与resources目录下,且与A.java具备相同的目录结构

二、利用Class.getClassLoader().getResourceAsStream(String path)class

    默认则是从ClassPath根下获取,path不能以’/'开头,最终是由ClassLoader获取资源。容器

//调用与A.java对应的A.properties
InputStream is = A.class.getClassLoader().getResourceAsStream("package1/A.properties")
Properties properties = new Properties();
properties.load(is);
String name = properties.getProperty("name");

三、ServletContext. getResourceAsStream(String path)im

    默认从WebAPP根目录下取资源,Tomcat下path是否以’/'开头无所谓,固然这和具体的容器实现有关。项目

相关文章
相关标签/搜索