讀取屬性值和修改其值
package com.chehaha.theme;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.jasper.tagplugins.jstl.core.Url;
import com.chehaha.common.exception.BizException;
/*
* 讀取Properties綜合類,預設繫結到classpath下的config.properties檔案。
*/
public class PropertiesUtil {
/**
*
*/
public static Map<String,String> readAllProperties() throws FileNotFoundException,IOException {
Map<String,String> map= new HashMap<>();
Properties prop = new Properties();
//讀取屬性檔案a.properties
InputStream in = new BufferedInputStream (new FileInputStream("application-dev.yml"));
prop.load(in); ///載入屬性列表
Iterator<String> it=prop.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
map.put(key, prop.getProperty(key));
System.out.println(key+":"+prop.getProperty(key));
}
return map;
}
/**
* 設定某個key的值,並儲存至檔案。
* @param key key值
* @return key 鍵對應的值
*/
public static void setValue(String key,String value) throws IOException {
Properties prop = new Properties();
try{
//讀取屬性檔案
InputStream in = new BufferedInputStream (new FileInputStream("application-dev.yml"));
prop.load(in); ///載入屬性列表
in.close();
///儲存屬性到檔案
FileOutputStream oFile = new FileOutputStream("application-dev.yml", true);//true表示追加開啟
prop.setProperty("testconfig", "10086");
prop.store(oFile, "The New properties file");
oFile.close();
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String[] args) {
Properties prop = new Properties();
try{
InputStream in = new BufferedInputStream (new FileInputStream("application-dev.yml"));
prop.load(in); ///載入屬性列表
String property = prop.getProperty("testconfig");
System.out.println(property);
in.close();
///儲存屬性到b.properties檔案
FileOutputStream oFile = new FileOutputStream("application-dev.yml", true);//true表示追加開啟
prop.setProperty("testconfig", "10086");
prop.store(oFile, null);
oFile.close();
}
catch(Exception e){
System.out.println(e);
}
}
}