** 首發于www.dongxiaoxia.xyz **
一.getResourceAsStream
方法使用
**這里的getResourceAsStream
主要是針對Class
與ClassLoader
而言的 **
-
Class.getResourceAsStream(String path)
: path 不以’/'開頭時默認是從此類所在的包下取資源,以’/'開頭則是從ClassPath根下獲取。其只是通過path構造一個絕對路徑,最終還是由ClassLoader獲取資源。 -
Class.getClassLoader.getResourceAsStream(String path)
:默認則是從ClassPath根下獲取,path不能以’/'開頭,最終是由ClassLoader獲取資源。 -
ServletContext. getResourceAsStream(String path)
:默認從WebAPP根目錄下取資源,Tomcat下path是否以’/'開頭無所謂,當然這和具體的容器實現有關。
獲取
Class
方法:
1.XX.class
2.this.getClass()
獲取ClassLoader
方法:
1.Thread.currentThread().getContextClassLoader()
2.Class.getClassLoader
**getResourceAsStream
用法大致有以下幾種: **
第一: 要加載的文件和.class文件在同一目錄下,例如:com.x.y 下有類me.class ,同時有資源文件myfile.xml
那么,應該有如下代碼:
me.class.getResourceAsStream("myfile.xml");
第二:在me.class目錄的子目錄下,例如:com.x.y 下有類me.class ,同時在 com.x.y.file 目錄下有資源文件myfile.xml
那么,應該有如下代碼:
me.class.getResourceAsStream("file/myfile.xml");
第三:不在me.class目錄下,也不在子目錄下,例如:com.x.y 下有類me.class ,同時在 com.x.file 目錄下有資源文件myfile.xml
那么,應該有如下代碼:
me.class.getResourceAsStream("/com/x/file/myfile.xml");
總結一下,可能只是兩種寫法
第一:前面有 “ / ”
“ / ”代表了工程的根目錄,例如工程名叫做myproject,“ / ”代表了myproject
me.class.getResourceAsStream("/com/x/file/myfile.xml");
第二:前面沒有 “ / ”
代表當前類的目錄
me.class.getResourceAsStream("myfile.xml");
me.class.getResourceAsStream("file/myfile.xml");
缺點:
getResourceAsStream讀取的文件路徑只局限與工程的源文件夾中,包括在工程src根目錄下,以及類包里面任何位置,但是如果配置文件路徑是在除了源文件夾之外的其他文件夾中時,該方法是用不了的。
二.Properties
配置文件的讀取
1.使用Apache Commons Configuration
讀取配置信息
第三方標準jar包,容易使用,擁有眾多功能,不用重復造輪子,但是為了讀取一個配置文件就要引入一個jar包時就要考慮一下了。
2.Spring ResourceLoader
Spring 能支持入參路徑的很多方式,包括已 " /"、"classpath" 開頭。
如果你想在項目中使用 Spring 提供的默認配置文件載入實現,可以這樣書寫你的代碼。
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("log4j.properties");
Properties props = new Properties();
props.load(resource.getInputStream());
缺點:依賴于Spring框架,難以通用, 如果用Spring框架應該用Spring統一管理配置文件,而不是當作一個工具類使用。
3.通過 java.util.ResourceBundle
對象 操作
通過該方式僅能讀取配置文件而已,不能進行寫操作。示例:
// ResourceBundle rb = ResourceBundle.getBundle("配置文件相對工程根目錄的相對路徑(不含擴展名)");
ResourceBundle rb = ResourceBundle.getBundle("config");
String name = rb.getString("name");
java自帶的類,使用非常簡單,代碼量還少。但是功能略微簡單。
4.通過Properties
對象手動寫個工具類
通過Properties對象自定義封裝,更能滿足自己需要的要求。
/**
* 根據Properties配置文件名稱獲取配置文件對象
*
* @param propsFileName Properties配置文件名稱(從ClassPath根下獲取)
* @return Properties對象
*/
private Properties getProperties(String propsFileName) {
if (propsFileName == null || propsFileName.equals("")) throw new IllegalArgumentException();
Properties properties = new Properties();
InputStream inputStream = null;
try {
try {
if (propsFileName.lastIndexOf(PROPERTY_FILE_SUFFIX) == -1) {//加入文件名后綴
propsFileName += PROPERTY_FILE_SUFFIX;
}
//寫法1:
// inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propsFileName);
//寫法2:
// URL url = Thread.currentThread().getContextClassLoader().getResource(propsFileName);
// inputStream = url.openStream();
//寫法3:
// inputStream = PropertiesLoader.class.getClassLoader().getResourceAsStream(propsFileName);
//寫法4:
// URL url = PropertyUtil.class.getClassLoader().getResource(propsFileName);
// inputStream = url.openStream();
//寫法5:
inputStream = PropertiesLoader.class.getResourceAsStream("/" + propsFileName);
if (null != inputStream) properties.load(inputStream);
} finally {
if (null != inputStream) {
inputStream.close();
}
}
} catch (IOException e) {
// LOGGER.error("加載屬性文件出錯!", e);
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
return properties;
}
三.jar包讀取外部和內部配置文件
1.獲取文件的方式
把項目打成jar包發布后jar中的文件就不能通過File file=new File("文件路徑")的方式來讀取文件了。
錯誤方式:
URL url = DBHelper.class.getClassLoader().getResource(configName);
URL url = DBHelper.class.getResource("/db.properties");
從依賴的Jar包中讀取文件, Jar包內的文件是無法用File讀取的,只能用Stream的方式讀取。
正確方式:
InputStream inputStraean = DBHelper.class.getClassLoader().getResourceAsStream("db.properties")
結論:不能傳文件路徑,只能傳輸入流
2.測試獲取文件的各種情況
待測試jar包目錄:
測試目錄引用進來的maven目錄

測試項目目錄
待測試jar包運行結果:
測試項目運行結果
根據測試得到的結果:
- 項目與項目引入jar包的文件都是在classpath下面的,也就是可以通過getResourceAsStream獲取,jar包與項目的獲取方法沒有分別,也就是說,獲取jar內部與外部文件的方式是一樣的。
- 如果項目與jar包在相對于classpath下有同樣的文件,則以項目的文件覆蓋jar包里面的文件。
- jar包里面沒有d.properties,所有jar包里面測試運行沒有找到,但是到了項目里面,在項目下創建d.properties,可是可以發現該文件的。
- 項目可以獲取項目的文件
項目可以獲取jar包里面的文件
jar包可以獲取項目的文件
jar包可以獲取jar包里面的文件
項目與jar包同時存在該文件,則以項目的文件優先
因此,如果開發一個庫或jar包,可以保留一份默認配置在jar包里面,也可以把配置文件放到客戶端配置,檢測時做處理,如果客戶端配置該文件,則以客戶端的配置為先,沒有找到就用默認配置文件,或者別的處理(拋異常等。。。),slf4j配置我猜也是這樣子吧=_=。
四.Properties配置文件讀取工具類
package xyz.dongxiaoxia.commons.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.logging.Logger;
/**
* Properties文件載入工具,可載入多個Properties文件,相同屬性在最后載入的文件中的值將會覆蓋之前的值,但以System的Property優先。
*
* @author dongxiaoxia
* @create 2016-07-01 23:03
*/
public class PropertiesLoader {
private static Logger logger = Logger.getLogger(PropertiesLoader.class.getName());
/**
* .properties屬性文件名后綴
*/
public static final String PROPERTY_FILE_SUFFIX = ".properties";
private final Properties properties;
public PropertiesLoader(String... propsFileNames) {
properties = loadProperties(propsFileNames);
}
public PropertiesLoader(String propsFileName) {
properties = getProperties(propsFileName);
}
public PropertiesLoader(InputStream inputStream) {
properties = loadProperties(inputStream);
}
public Properties getProperties() {
return properties;
}
/**
* 取出Property,但與System的Property優先,取不到返回空字符串。
*
* @param key
* @return
*/
private String getValue(String key) {
String systemProperty = System.getProperty(key);
if (systemProperty != null) {
return systemProperty;
}
if (properties.containsKey(key)) {
return properties.getProperty(key);
}
return "";
}
/**
* 取出String類型的Property,但與System的Property優先,如果都為NUll則拋出異常。
*
* @param key
* @return
*/
public String getProperty(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return value;
}
/**
* 取出String類型的Property,但以System的Property優先,如果都為Null則返回Default值。
*
* @param key
* @param defaultValue
* @return
*/
public String getProperty(String key, String defaultValue) {
String value = getValue(key);
return value != null ? value : defaultValue;
}
/**
* 取出Integer類型的Property。但以System的Property優先,如果都為null或內容錯誤則拋異常。
*
* @param key
* @return
*/
public Integer getInteger(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return Integer.valueOf(value);
}
/**
* 取出Integer類型的Property,但以System的Property優先。如果都為null則返回默認值,如果內容錯誤則拋異常。
*
* @param key
* @param defaultValue
* @return
*/
public Integer getInteger(String key, Integer defaultValue) {
String value = getValue(key);
return value != null ? Integer.valueOf(value) : defaultValue;
}
/**
* 取出Double類型的Property,但以System的Property優先,如果都為null或內容錯誤則拋異常。
*
* @param key
* @return
*/
public Double getDouble(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return Double.valueOf(value);
}
/**
* 取出Double類型的Property,但以System的Property優先,如果都為null則返回默認值,如果內容錯誤則拋異常。
*
* @param key
* @param defaultValue
* @return
*/
public Double getDouble(String key, Double defaultValue) {
String value = getValue(key);
return value != null ? Double.valueOf(value) : defaultValue;
}
/**
* 取出Boolean類型的Property,但以System的Property優先,如果都為null則拋出異常,如果內容不是true/false則返回false。
*
* @param key
* @return
*/
public Boolean getBoolean(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return Boolean.valueOf(value);
}
/**
* 取出Boolean類型的Property,但以System的Property優先,如果都為null則返回默認值,如果內容不為true/false則返回false。
*
* @param key
* @param defaultValue
* @return
*/
public Boolean getBoolean(String key, boolean defaultValue) {
String value = getValue(key);
return value != null ? Boolean.valueOf(value) : defaultValue;
}
public Set<Object> getAllKey() {
return properties.keySet();
}
public Collection<Object> getAllValues() {
return properties.values();
}
public Map<String, Object> getAllKeyValue() {
Map<String, Object> mapAll = new HashMap<>();
Set<Object> keys = getAllKey();
for (Object key1 : keys) {
String key = key1.toString();
mapAll.put(key, properties.get(key));
}
return mapAll;
}
/**
* 根據Properties配置文件名稱獲取配置文件對象
*
* @param propsFileName Properties配置文件名稱(從ClassPath根下獲取) 可以不帶擴展名
* eg.根目錄下有個common.properties,那么可以傳“common”或者“common.properties”
* 根目錄下有個config文件夾,里面存在common.properties,那么可以傳“config/common”或者“config/common.properties”
* @return Properties對象
*/
private Properties getProperties(String propsFileName) {
if (propsFileName == null || propsFileName.equals("")) throw new IllegalArgumentException();
Properties properties = new Properties();
InputStream inputStream = null;
try {
try {
if (propsFileName.lastIndexOf(PROPERTY_FILE_SUFFIX) == -1) {//加入文件名后綴
propsFileName += PROPERTY_FILE_SUFFIX;
}
//寫法1:
// inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propsFileName);
//寫法2:
// URL url = Thread.currentThread().getContextClassLoader().getResource(propsFileName);
// inputStream = url.openStream();
//寫法3:
inputStream = PropertiesLoader.class.getClassLoader().getResourceAsStream(propsFileName);
//寫法4:
// URL url = PropertyUtil.class.getClassLoader().getResource(propsFileName);
// inputStream = url.openStream();
//寫法5:
// inputStream = PropertiesLoader.class.getResourceAsStream("/" + propsFileName);
if (null != inputStream) properties.load(inputStream);
} finally {
if (null != inputStream) {
inputStream.close();
}
}
} catch (IOException e) {
// LOGGER.error("加載屬性文件出錯!", e);
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
return properties;
}
/**
* 載入多個文件
*
* @param propsFileNames
* @return
*/
private Properties loadProperties(String... propsFileNames) {
Properties pros = new Properties();
for (String propsFileName : propsFileNames) {
InputStream inputStream = null;
try {
inputStream = PropertiesLoader.class.getClassLoader().getResourceAsStream(propsFileName);
pros.load(inputStream);
} catch (Exception e) {
logger.info("Could not load properties from path:" + propsFileName + "," + e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.info(e.getMessage());
}
}
}
return pros;
}
/**
* 根據輸入流載入Properties對象
*
* @param inputStream
* @return
*/
private Properties loadProperties(InputStream inputStream) {
Properties pros = new Properties();
// pros.load(inputStream);
try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8")) {
pros.load(inputStreamReader);
} catch (Exception e) {
logger.info(e.getMessage());
}
return pros;
}
}
更多請查看GItHub PropertiesLoader類