【轉】Java工具類——資原始檔解析類PropertiesUtil
阿新 • • 發佈:2019-02-18
- package com.luang.util.properties;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.URI;
- import java.util.Enumeration;
-
import java.util.HashMap;
- import java.util.Map;
- import java.util.Properties;
- import java.util.ResourceBundle;
- /**
- *
- * PropertiesUtil.java
- *
- * @desc properties 資原始檔解析工具
- * @author Guoxp
- * @datatime Apr 7, 2013 3:58:45 PM
- *
- */
- publicclass PropertiesUtil {
- private Properties props;
-
private
- public PropertiesUtil(String fileName){
- readProperties(fileName);
- }
- privatevoid readProperties(String fileName) {
- try {
- props = new Properties();
- InputStream fis =getClass().getResourceAsStream(fileName);
-
props.load(fis);
- uri = this.getClass().getResource("/dbConfig.properties").toURI();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 獲取某個屬性
- */
- public String getProperty(String key){
- return props.getProperty(key);
- }
- /**
- * 獲取所有屬性,返回一個map,不常用
- * 可以試試props.putAll(t)
- */
- public Map getAllProperty(){
- Map map=new HashMap();
- Enumeration enu = props.propertyNames();
- while (enu.hasMoreElements()) {
- String key = (String) enu.nextElement();
- String value = props.getProperty(key);
- map.put(key, value);
- }
- return map;
- }
- /**
- * 在控制檯上打印出所有屬性,除錯時用。
- */
- publicvoid printProperties(){
- props.list(System.out);
- }
- /**
- * 寫入properties資訊
- */
- publicvoid writeProperties(String key, String value) {
- try {
- OutputStream fos = new FileOutputStream(new File(uri));
- props.setProperty(key, value);
- // 將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
- props.store(fos, "『comments』Update key:" + key);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- publicstaticvoid main(String[] args) {
- PropertiesUtil util=new PropertiesUtil("src/dbConfig.properties");
- util.writeProperties("dbtype", "MSSQL");
- }
- }