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是否以’/'開頭無所謂,固然這和具體的容器實現有關。項目

相關文章
相關標籤/搜索