1、引言
java開發中,經常需要讀取配置文件,有時即使我們方法是對的,但是就是讀取不到需要的內容,會報下面的錯:
java.io.FileNotFoundException: sr/configure/config.properties (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at com.test.properties.TestProperties.getProperties_2(TestProperties.java:118)
at com.test.properties.TestProperties.main(TestProperties.java:253)
或者這個錯:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at com.test.properties.TestProperties.getProperties_3(TestProperties.java:174)
at com.test.properties.TestProperties.main(TestProperties.java:258)
等等。
2、幾種讀取方式
2.1 基於ClassLoder讀取配置文件
Properties properties = new Properties();
// 使用ClassLoader加載properties配置文件生成對應的輸入流
InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/config.properties");
// 使用properties對象加載輸入流
properties.load(in);
//獲取key對應的value值
properties.getProperty(String key);
注意: 該方式只能讀取類路徑下的配置文件,有侷限但是如果配置文件在類路徑下比較方便。
2.2 基於 InputStream 讀取配置文件
Properties properties = new Properties();
// 使用InPutStream流讀取properties文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));
properties.load(bufferedReader);
// 獲取key對應的value值
properties.getProperty(String key);
注意: 該方式的優點在於可以讀取任意路徑下的配置文件
2.3 通過 java.util.ResourceBundle 類來讀取,這種方式比使用 Properties 要方便一些
通過 ResourceBundle.getBundle() 靜態方法來獲取(ResourceBundle是一個抽象類),這種方式來獲取properties屬性文件不需要加.properties後綴名,只需要文件名即可
//config爲屬性文件名,放在包com.test.config下,如果是放在src下,直接用config即可
ResourceBundle resource = ResourceBundle.getBundle("com/test/config/config");
String value = resource.getString("key");
從 InputStream 中讀取,獲取 InputStream 的方法和上面一樣,不再贅述
ResourceBundle resource = new PropertyResourceBundle(inStream);
注意: 在使用中遇到的最大的問題可能是配置文件的路徑問題,如果配置文件入在當前類所在的包下,那麼需要使用包名限定,如:config.properties入在com.test.config包下,則要使用com/test/config/config.properties(通過Properties來獲取)或com/test/config/config(通過ResourceBundle來獲取);屬性文件在src根目錄下,則直接使用config.properties或config即可。
2.4 根據文件名稱獲取屬性配置文件對象–自動搜索文件路徑
見案例代碼。
3、案例代碼
先看目錄結構
package com.test.properties;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Properties;
import java.util.ResourceBundle;
//import org.springframework.core.io.support.PropertiesLoaderUtils;
/**
*
* @ClassName: TestProperties
* @Description: 獲取配置文件信息
* @date: 2017年11月25日 上午10:56:00
* @version: 1.0.0
*/
public class TestProperties {
/**
*
* @Title: printAllProperty
* @Description: 輸出所有配置信息
* @param props
* @return void
* @throws
*/
private static void printAllProperty(Properties props)
{
@SuppressWarnings("rawtypes")
Enumeration en = props.propertyNames();
while (en.hasMoreElements())
{
String key = (String) en.nextElement();
String value = props.getProperty(key);
System.out.println(key + " : " + value);
}
}
/**
* 根據key讀取value
*
* @Title: getProperties_1
* @Description: 第一種方式:根據文件名使用spring中的工具類進行解析
* filePath是相對路勁,文件需在classpath目錄下
* 比如:config.properties在包com.test.config下,
* 路徑就是com/test/config/config.properties
*
* @param filePath
* @param keyWord
* @return
* @return String
* @throws
*/
// public static String getProperties_1(String filePath, String keyWord){
// Properties prop = null;
// String value = null;
// try {
// // 通過Spring中的PropertiesLoaderUtils工具類進行獲取
// prop = PropertiesLoaderUtils.loadAllProperties(filePath);
// // 根據關鍵字查詢相應的值
// value = prop.getProperty(keyWord);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return value;
// }
/**
* 讀取配置文件所有信息
*
* @Title: getProperties_1
* @Description: 第一種方式:根據文件名使用Spring中的工具類進行解析
* filePath是相對路勁,文件需在classpath目錄下
* 比如:config.properties在包com.test.config下,
* 路徑就是com/test/config/config.properties
*
* @param filePath
* @return void
* @throws
*/
// public static void getProperties_1(String filePath){
// Properties prop = null;
// try {
// // 通過Spring中的PropertiesLoaderUtils工具類進行獲取
// prop = PropertiesLoaderUtils.loadAllProperties(filePath);
// printAllProperty(prop);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
/**
* 根據key讀取value
*
* @Title: getProperties_2
* @Description: 第二種方式:使用緩衝輸入流讀取配置文件,然後將其加載,再按需操作
* 絕對路徑或相對路徑, 如果是相對路徑,則從當前項目下的目錄開始計算,
* 如:當前項目路徑/config/config.properties,
* 相對路徑就是config/config.properties
*
* @param filePath
* @param keyWord
* @return
* @return String
* @throws
*/
public static String getProperties_2(String filePath, String keyWord){
Properties prop = new Properties();
String value = null;
try {
// 通過輸入緩衝流進行讀取配置文件
InputStream InputStream = new BufferedInputStream(new FileInputStream(new File(filePath)));
// 加載輸入流
prop.load(InputStream);
// 根據關鍵字獲取value值
value = prop.getProperty(keyWord);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
/**
* 讀取配置文件所有信息
*
* @Title: getProperties_2
* @Description: 第二種方式:使用緩衝輸入流讀取配置文件,然後將其加載,再按需操作
* 絕對路徑或相對路徑, 如果是相對路徑,則從當前項目下的目錄開始計算,
* 如:src/configure/config.properties;絕對路徑就是文件所在的文件系統路徑。
*
*
* @param filePath
* @return void
* @throws
*/
public static void getProperties_2(String filePath){
Properties prop = new Properties();
try {
// 通過輸入緩衝流進行讀取配置文件
InputStream InputStream = new BufferedInputStream(new FileInputStream(new File(filePath)));
// 加載輸入流
prop.load(InputStream);
printAllProperty(prop);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根據key讀取value
*
* @Title: getProperties_3
* @Description: 第三種方式:
* 相對路徑, properties文件需在classpath目錄下,
* 比如:config.properties在包com.test.config下,
* 路徑就是/com/test/config/config.properties
* @param filePath
* @param keyWord
* @return
* @return String
* @throws
*/
public static String getProperties_3(String filePath, String keyWord){
Properties prop = new Properties();
String value = null;
try {
InputStream inputStream = TestProperties.class.getResourceAsStream(filePath);
prop.load(inputStream);
value = prop.getProperty(keyWord);
} catch (IOException e) {
e.printStackTrace();
}
return value;
}
/**
* 讀取配置文件所有信息
*
* @Title: getProperties_3
* @Description: 第三種方式:
* 相對路徑, properties文件需在classpath目錄下,
* 比如:config.properties在包com.test.config下,
* 路徑就是/com/test/config/config.properties
* @param filePath
* @return
* @throws
*/
public static void getProperties_3(String filePath){
Properties prop = new Properties();
try {
InputStream inputStream = TestProperties.class.getResourceAsStream(filePath);
prop.load(inputStream);
printAllProperty(prop);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getPro_4(String filePath,String key) {
//config爲屬性文件名,放在包com.test.config下,如果是放在src下,直接用config即可
//即 com/test/conifg/config
ResourceBundle resource = ResourceBundle.getBundle(filePath);
String value = resource.getString(key);
return value;
}
/**根據文件名稱獲取屬性配置文件對象--自動搜索文件路徑
*
* @param fileName 文件名稱
* 成功--返回對象;
* 失敗--返回null;
*/
public static Properties getPropertyByFileName(String fileName){
Properties prop = new Properties();
//ClassLoader classLoader = Thread.currentThread().getContextClassLoader();//返回該線程的上下文
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
try {
BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream));
String input = null;
//每讀一行進行一次寫入動作
while((input = bufReader.readLine()) != null){
if(!(input.length()==0) && input.startsWith("#") == false){
input = input.trim();
String[] split = input.split("=");
if(split != null && split.length == 2){
prop.setProperty(split[0].trim(), split[1].trim());
}
}
}
}catch(Exception ex)
{
ex.printStackTrace();
}finally{
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return prop;
}
public static void main(String[] args) {
// 注意路徑問題
// String properties_1 = getProperties_1("com/test/config/config.properties", "wechat_appid");
// System.out.println("wechat_appid = " + properties_1);
// getProperties_1("com/test/config/config.properties");
System.out.println("*********************************************");
// 注意路徑問題
String properties_2 = getProperties_2("src/configure/config.properties", "jdbc.url");
System.out.println("jdbc.url = " + properties_2);
// getProperties_2("configure/configure.properties");
System.out.println("*********************************************");
// 注意路徑問題
String properties_3 = getProperties_3("/com/test/conifg/config.properties", "wechat_appid");
System.out.println("wechat_appid = " + properties_3);
// getProperties_3("/com/test/config/config.properties");
System.out.println("*********************************************");
String properties_4 = getPro_4("com/test/conifg/config", "wechat_appid");
System.out.println("wechat_appid = " + properties_4);
System.out.println("*********************************************");
System.out.println(getPropertyByFileName("config2.properties"));
}
}
如果您能看到這裏,但是還是搞不定,可以檢查一下你的properties文件命名是否對的,有沒有在命名最後多了個不起眼的空格等等。