1. 程式人生 > 其它 >讀取Properties工具類

讀取Properties工具類

技術標籤:Javajava

嘗試一下封裝一個讀取Properties工具類,自己大概看了看DBUtils和Druid原始碼,學習一下封裝思想,希望有大佬指點。

public class PropertiesUtil {

    private Properties properties = null;
    private String fileName = null;
    private Logger log = Logger.getLogger(PropertiesUtil.class);

    public PropertiesUtil(){
    }

    public
PropertiesUtil(String fileName){ this.fileName = fileName; } private void creatProperties(){ if(this.fileName == null){ log.error("PropertiesUtil|error|配置檔案未設定"); throw new RuntimeException("配置檔案未設定"); } log.info("PropertiesUtil|info|fileName:"
+ this.fileName); if(!this.fileName.endsWith(".properties")){ log.error("PropertiesUtil|error|檔案格式錯誤"); throw new RuntimeException("檔案格式錯誤"); } this.properties = new Properties(); } public String getValue(String key)
{ return this.getValue(null,key); } /* 通過key值讀取配置檔案的單一值 */ public String getValue(String fileName,String key) throws RuntimeException{ if(fileName != null){ this.fileName = fileName; } if(this.properties == null){ creatProperties(); fileReadLoad(); } Object val = this.properties.get(key); if(val == null){ log.error("PropertiesUtil|error|沒有找到對應的值!"); throw new RuntimeException("沒有找到對應的值!"); } return val.toString(); } public void setValue(Map<String, String> map){ this.setValue(null,map); } public void setValue(String fileName,Map<String, String> map){ if (fileName != null){ this.fileName = fileName; } creatProperties(); Set<String> keySet = map.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()){ String key = iterator.next(); setProperties(key,map.get(key)); } fileOutLoad(); } public void setValue(String key,String val){ this.setValue(this.fileName,key,val); } /* 向配置檔案裡儲存資料 */ public void setValue(String fileName,String key,String val){ if (fileName != null){ this.fileName = fileName; } creatProperties(); setProperties(key,val); fileOutLoad(); } private void setProperties(String key,String val){ this.properties.setProperty(key,val); } /* 載入配置檔案 */ private void fileReadLoad(){ InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(this.fileName); if(in == null){ log.error("PropertiesUtil|error|配置檔案設定錯誤"); throw new RuntimeException("配置檔案設定錯誤"); } try { this.properties.load(in); } catch (IOException e) { e.printStackTrace(); } } /* 儲存配置檔案 */ private void fileOutLoad(){ File file = new File("bin" + File.separator + this.fileName); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file); this.properties.store(fileOutputStream, String.valueOf(System.nanoTime() + "--" + Math.random())); } catch (Exception e) { log.error("PropertiesUtil|error|" + e.getMessage()); e.printStackTrace(); }finally { try { if(fileOutputStream != null){ fileOutputStream.close(); } } catch (IOException e) { log.error("PropertiesUtil|error|" + e.getMessage()); e.printStackTrace(); } if(this.properties != null){ this.properties.clear(); } } } }