在Java中屬性操做類是一個很重要的類,而要想明白屬性操做類的做用,就必須先要清楚什麼是屬性文件,在屬性文件中含有多個屬性,每一個屬性就是直接用字符串表示出來的"key=value 鍵/值對", 而若是要想輕鬆操做這些屬性須要使用Properties類完成.java
public class Properties extends Hashtable<Object,Object> 複製代碼
編號 | 方法名稱 | 類型 | 描述 |
---|---|---|---|
1 | public Properties() | 構造 | 建立一個無默認值的空屬性類 |
2 | public Properties(Properties props) | 構造 | 建立一個帶有指定默認值的空屬性類 |
3 | public String getProperty(String key) | 普通方法 | 根據屬性的key取得屬性的value,若是沒有,將放回null |
4 | public String getProperty(String key, String defaultValue) | 普通方法 | 根據屬性的key取得屬性的value,若是沒有,將返回defaultValue |
5 | public Object setProperty(String key, String value) | 普通方法 | 設置屬性 |
6 | public void list(PrintStream out) | 普通方法 | 屬性打印 |
7 | public void load(InputStream inStream) | 普通方法 | 將輸入流中取出所有的屬性內容 |
8 | public void loadFromXML(InputStream in) | 普通方法 | 從XML文件格式中讀取內容 |
9 | public void store(OutputStream out, String comments) | 普通方法 | 將屬性內容經過輸出流輸出,同時聲明屬性的註釋內容 |
10 | public void storeToXML(OutputStream os, String comment) | 普通方法 | 以XML文件格式輸出屬性,默認編碼 |
11 | public void storeToXML(OutputStream os, String comment, String encoding) | 普通方法 | 以XML文件格式輸出屬性,用戶指定默認編碼 |
實際開發中咱們使用Properties的功能相似於存儲的數據爲Map<String,String>都是字符串的形式web
示例1:設置和取得屬性數組
主要使用setProperty()和getProperty()方法設置和獲取屬性,存儲的數據類型都是String瀏覽器
package com.shxt.demo06;
import java.util.Properties;
public class Demo01 {
public static void main(String[] args) {
Properties props = new Properties(); //建立Properties對象
//設置屬性
props.setProperty("title","胖先森博客");
props.setProperty("version","v1.0");
props.setProperty("db","MySQL 5.7");
//獲取屬性
System.out.println("1.title屬性存在:"+props.getProperty("title"));
System.out.println("2.name屬性不存在:"+props.getProperty("name"));
System.out.println("3.name屬性不存在,顯示默認值:"+props.getProperty("name","胖先森"));
}
}
/* 運行結果: 1.title屬性存在:胖先森博客 2.name屬性不存在:null 3.name屬性不存在,顯示默認值:胖先森 */
複製代碼
示例2:保存屬性到普通的屬性文件session
package com.shxt.demo06;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Demo02 {
public static void main(String[] args) {
Properties props = new Properties(); //建立Properties對象
//設置屬性
props.setProperty("title","胖先森博客");
props.setProperty("version","v1.0");
props.setProperty("db","MySQL 5.7");
//設置屬性文件的保存路徑,使用絕對路徑
//關於文件的操做,咱們在後面J2EE文件上傳的時候會再次說明
File file = new File("D:/sys.properties");
try {
props.store(new FileOutputStream(file),"system config");
} catch (IOException e) {
e.printStackTrace();
}
}
}
複製代碼
運行結果:app
說明:若是是中文會使用Unicode進行轉換jsp
示例3:從屬性文件中讀取內容ide
package com.shxt.demo06;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Demo03 {
public static void main(String[] args) {
Properties props = new Properties(); //建立Properties對象
//跟磁盤中的文件創建聯繫
File file = new File("D:/sys.properties");
try {
//讀取屬性文件
props.load(new FileInputStream(file));
//獲取屬性
System.out.println("getProperty():"+props.getProperty("title"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* 運行結果: getProperty():胖先森博客 */
複製代碼
下面的簡單瞭解就好工具
示例4:將屬性文件保存到XML文件中編碼
package com.shxt.demo06;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Demo04 {
public static void main(String[] args) {
Properties props = new Properties(); //建立Properties對象
//設置屬性
props.setProperty("title","胖先森博客");
props.setProperty("version","v1.0");
props.setProperty("db","MySQL 5.7");
//跟磁盤中的文件創建聯繫,文件的後綴名必須爲.xml
File file = new File("D:/sys.xml");
try {
props.storeToXML(new FileOutputStream(file),"system config");
} catch (IOException e) {
e.printStackTrace();
}
}
}
複製代碼
運行結果:
示例5:從XML文件中讀取屬性
package com.shxt.demo06;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Demo05 {
public static void main(String[] args) {
Properties props = new Properties(); //建立Properties對象
//跟磁盤中的文件創建聯繫
File file = new File("D:/sys.xml");
try {
//讀取XML文件
props.loadFromXML(new FileInputStream(file));
//獲取屬性
System.out.println("getProperty():"+props.getProperty("title"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* 運行結果: getProperty():胖先森博客 */
複製代碼
不推薦的寫法
#正確的properties配置文件
aaa=wu\
kong
b
bb = bajie
複製代碼
推薦的寫法
#格式良好的properties文件
aaa=wukong
bbb=bajie
複製代碼
(1) 使用java.util.Properties類的load()方法
你須要提供一共絕對路徑讀取數據,"D:/sys.properties"相似的路徑,我我的不怎麼推薦使用
package com.shxt.demo06;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Demo06 {
public static void main(String[] args) {
Properties props = new Properties();
try {
props.load(new FileInputStream("D:/sys.properties"));
//獲取屬性
System.out.println("title屬性的值:"+props.getProperty("title"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
複製代碼
(2) 使用java.util.ResourceBunld類的getBundle()方法[掌握]
經過ResourceBundle.getBundle()
靜態方法來獲取(ResourceBundle是一個抽象類),這種方式來獲取properties屬性文件不須要加.properties後綴名,只須要文件名便可.
package com.shxt.demo06;
import java.util.ResourceBundle;
public class Demo07 {
public static void main(String[] args) {
ResourceBundle resouce = ResourceBundle.getBundle("sys");
//獲取屬性
System.out.println("title屬性的值:"+resouce.getString("title"));
}
}
複製代碼
package com.shxt.demo06;
import java.util.ResourceBundle;
public class Demo08 {
public static void main(String[] args) {
//sys爲屬性文件名,放在包com.shxt.demo06下,若是是放在src下,直接用sys便可
ResourceBundle resouce = ResourceBundle.getBundle("com/shxt/demo06/sys");
//獲取屬性
System.out.println("title屬性的值:"+resouce.getString("title"));
}
}
複製代碼
(3) 使用PropertyResourceBundle
package com.shxt.demo06;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
public class Demo09 {
public static void main(String[] args) {
try {
ResourceBundle resource = new PropertyResourceBundle(new FileInputStream("D:/sys.properties"));
//獲取屬性
System.out.println("title屬性的值:"+resource.getString("title"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
複製代碼
(4) 使用class變量的getResourceAsStream()方法
package com.shxt.demo06;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Demo11 {
public static void main(String[] args) {
// /config/sys.properties 從src的根目錄開始查找,記住這個"/"
// 若是沒有這個斜線,那麼會報空指針異常
InputStream in = Demo11.class.getResourceAsStream("/config/sys.properties");
Properties props = new Properties();
try {
props.load(in);
//獲取屬性
System.out.println("title屬性的值:"+props.getProperty("db"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
複製代碼
(5) 使用class.getClassLoader()所獲得的java.lang.ClassLoader的getResourceAsStream()方法
package com.shxt.demo06;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Demo12 {
public static void main(String[] args) {
InputStream in = Demo12.class.getClassLoader().getResourceAsStream("config/sys.properties");
Properties props = new Properties();
try {
props.load(in);
//獲取屬性
System.out.println("title屬性的值:"+props.getProperty("db"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
複製代碼
感受上就是少了一個斜線而已
(6) 使用java.lang.ClassLoader類的getSystemResourceAsStream()靜態方法[推薦]
package com.shxt.demo06;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Demo13 {
public static void main(String[] args) {
InputStream in = ClassLoader.getSystemResourceAsStream("config/sys.properties");
Properties props = new Properties();
try {
props.load(in);
//獲取屬性
System.out.println("title屬性的值:"+props.getProperty("db"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
複製代碼
7.補充:Servlet中可使用javax.servlet.ServletContext的getResourceAsStream()方法
InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);
複製代碼
這裏分享一個簡單的封裝的工具類
package com.pangsir.helper.properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
/** * 加載屬性文件 * * @author 劉文銘 * @see com.pangsir.helper.properties.PropertiesConfigHelper * @since 1.0 */
public class PropertiesConfigHelper {
private PropertiesConfigHelper(){}
//使用日誌輸出
private final static Logger logger = LoggerFactory.getLogger(PropertiesConfigHelper.class);
//設置後綴名
private final static String EXT = ".properties";
//實例化Properties對象
private static Properties configProperties = null;
/** * 加載properties文件 * * @param filepaths properties文件路徑 */
public static void load(String... filepaths) {
logger.debug("開始讀取properties文件 開始時間" + System.currentTimeMillis());
if(configProperties==null){
configProperties = new Properties();
}
//配置文件路徑
String configFilePath;
InputStream inputStream = null;
//遍歷filepathke數組
for (int i = 0; i < filepaths.length; i++) {
configFilePath = filepaths[i];
//讀取屬性文件後綴名爲.properties
try {
if (configFilePath.toLowerCase().endsWith(EXT)) {
inputStream = PropertiesConfigHelper.class.getClassLoader().getResourceAsStream(configFilePath);
configProperties.load(inputStream);
} else {
throw new RuntimeException("沒法讀取該文件: " + configFilePath);
}
logger.debug("文件 \"" + configFilePath + "\" 讀取 成功! 時間爲:" + System.currentTimeMillis());
} catch (Exception e) {
logger.debug("文件 \"" + configFilePath + "\" 讀取 失敗, 失敗異常信息:\\n" + e.getMessage());
throw new RuntimeException("文件 \"" + configFilePath + "\" 加載失敗", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
logger.debug("全部配置文件讀取完畢,當關閉文件FileInputStream時,異常信息 :\\n" + e.getMessage());
}
}
}
}
}
/** * 獲取 int 類型的配置屬性的value * * @param key 配置屬性的key * @param defaultValue 默認值 * @return 對應的配置屬性value,若是配置屬性的value不爲short類型或不存在對應的配置屬性,則返回 defaultValue */
public static Short getShortValue(String key, Short defaultValue) {
try {
return getShortValue(key);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/** * 獲取 short 類型的配置屬性的value * * @param key 配置屬性的key * @return 對應的配置屬性value */
public static Short getShortValue(String key) {
return Short.parseShort(configProperties.getProperty(key));
}
/** * 獲取 int 類型的配置屬性的value * * @param key 配置屬性的key * @param defaultValue 默認值 * @return 對應的配置屬性value,若是配置屬性的value不爲int類型或不存在對應的配置屬性,則返回 defaultValue */
public static int getIntegerValue(String key, Integer defaultValue) {
try {
return getIntegerValue(key);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/** * 獲取 int 類型的配置屬性的value * * @param key 配置屬性的key * @return 對應的配置屬性value */
public static Integer getIntegerValue(String key) {
return Integer.parseInt(configProperties.getProperty(key));
}
/** * 獲取 float 類型的配置屬性的value * * @param key 配置屬性的key * @param defaultValue 默認值 * @return 對應的配置屬性value,若是配置屬性的value不爲float類型或不存在對應的配置屬性,則返回 defaultValue */
public static Float getFloatValue(String key, float defaultValue) {
try {
return getFloatValue(key);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/** * 獲取 float 類型的配置屬性的value * * @param key 配置屬性的key * @return 對應的配置屬性value */
public static Float getFloatValue(String key) {
return Float.parseFloat(configProperties.getProperty(key));
}
/** * 獲取 double 類型的配置屬性的value * * @param key 配置屬性的key * @param defaultValue 默認值 * @return 對應的配置屬性value,若是配置屬性的value不爲double類型或不存在對應的配置屬性,則返回 defaultValue */
public static Double getDoubleValue(String key, double defaultValue) {
try {
return getDoubleValue(key);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/** * 獲取 Double 類型的配置屬性的value * * @param key 配置屬性的key * @return 對應的配置屬性value */
public static Double getDoubleValue(String key) {
return Double.parseDouble(configProperties.getProperty(key));
}
/** * 獲取 long 類型的配置屬性的value * * @param key 配置屬性的key * @param defaultValue 默認值 * @return 對應的配置屬性value,若是配置屬性的value不爲long類型或不存在對應的配置屬性,則返回 defaultValue */
public static Long getLongValue(String key, long defaultValue) {
try {
return getLongValue(key);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/** * 獲取 Long 類型的配置屬性的value * * @param key 配置屬性的key * @return 對應的配置屬性value */
public static Long getLongValue(String key) {
return Long.parseLong(configProperties.getProperty(key));
}
/** * 獲取 String 類型的配置屬性的value * * @param key 配置屬性的key * @param defaultValue 默認值 * @return 對應的配置屬性value,若是配置屬性的value爲""或不存在對應的配置屬性,則返回 defaultValue */
public static String getStringValue(String key, String defaultValue) {
String value = configProperties.getProperty(key);
return (value == null) ? defaultValue : getStringValue(key);
}
/** * 獲取 String 類型的配置屬性的value * * @param key 配置屬性的key * @return 對應的配置屬性value */
public static String getStringValue(String key) {
return configProperties.getProperty(key);
}
/** * 獲取 boolean 類型的配置屬性的value * * @param key 配置屬性的key * @param defaultValue 默認值 * @return 若是在配置文件中沒有定義此屬性,則返回 defaultValue; * 若是 value 爲y、on、yes 、true 或非 0 數值(均不區分大小寫) 則返回 true, 不然返回 false */
public static boolean getBooleanValue(String key, Boolean defaultValue) {
String value = configProperties.getProperty(key);
return (value == null) ? defaultValue : getBooleanValue(key);
}
/** * 獲取 boolean 類型的配置屬性的value * * @param key 配置屬性的key * @return 對應的配置屬性value */
public static Boolean getBooleanValue(String key) {
String value = configProperties.getProperty(key);
return ("y".equalsIgnoreCase(value)) || ("on".equalsIgnoreCase(value)) || ("yes".equalsIgnoreCase(value))
|| ("true".equalsIgnoreCase(value)) || (getIntegerValue(key, 0) != 0);
}
/** * 加載properties文件 * * @param filepath properties文件路徑 */
public static void write(String key, String value,String filepath){
if(configProperties==null){
configProperties = new Properties();
}
OutputStream outputStream = null;
try{
String base = PropertiesConfigHelper.class.getResource("/"+filepath).getPath();
java.net.URL url = PropertiesConfigHelper.class.getResource("/"+filepath);
File file = new File(url.toURI());
//判斷文件是否存在
if(!file.exists()){
file.createNewFile();
}
load(filepath);//加載文件
outputStream = new FileOutputStream(file);
configProperties.setProperty(key,value);
configProperties.store(outputStream,"");
}catch (Exception e){
throw new RuntimeException("文件 \"" + filepath + "\" 加載失敗", e);
}finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
logger.debug("全部配置文件修改完畢,FileOutputStream異常信息 :\\n" + e.getMessage());
}
}
}
}
}
複製代碼
重點:將properties文件的配置設置爲整個Web應用的全局變量實現方法,學到J2EE階段再使用下面的方式
WEB域的簡單說明:
Web應用中的變量存放在不一樣的jsp對象中,會有不同的做用域,四種不一樣的做用域排序是 pageContext < request < session < application;
思路說明:
利用ServletContextListener監聽器,一旦應用加載,就將properties的值存儲到application當中.
如今須要在全部的jsp中都能經過EL表達式讀取到properties中的屬性,而且是針對全部的會話,故這裏利用application做用域,那麼何時將properties中的屬性存儲到application呢?由於是將properties的屬性值做爲全局的變量以方便任何一次EL的獲取,因此在web應用加載的時候就將值存儲到application當中.
這裏就要利用ServletContextListener:
具體步驟:
/** * 設值全局變量 */
public class PropertyListenter implements ServletContextListener {
private static final Logger logger = (Logger) LoggerFactory.getLogger(PropertyListenter.class);
@Override
public void contextDestroyed(ServletContextEvent context) {}
@Override
public void contextInitialized(ServletContextEvent sce) {
/** * 讀取properties文件 */
Properties properties = new Properties();
InputStream in = null;
try {
//經過類加載器進行獲取properties文件流
in = PropertiesUtil.class.getClassLoader().getResourceAsStream("sys.properties");
properties.load(in);
} catch (FileNotFoundException e) {
logger.error("未找到properties文件");
} catch (IOException e) {
logger.error("發生IOException異常");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error("properties文件流關閉出現異常");
}
}
/** * 將properties文件轉存到map.關鍵步驟 */
Map<String, String> pros = new HashMap<String,String>((Map)properties);
/** * 將Map經過ServletContext存儲到全局做用域中 */
ServletContext sct=sce.getServletContext();
sct.setAttribute("pros", pros);
}
}
複製代碼