java配置文件讀取工具類

此類用於讀取和存儲配置文件等,已經封裝好,可直接使用,也不須要導入其他的jar包java

package utils; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * 讀寫配置文件 * 路徑格式 : src/user.properties * @author cyh * */
public class PropertyReader { private static final String BASEPATH = "D:/java/"; //根據Key讀取Value
    public static String GetValueByKey(String filename, String key) { Properties pps = new Properties(); try { InputStream in = new BufferedInputStream (new FileInputStream(BASEPATH+filename)); pps.load(in); String value = pps.getProperty(key)+""; if(("null").equals(value)) { return null; } in.close(); return value; }catch (IOException e) { // e.printStackTrace();
            return null; } } //讀取Properties的所有信息
    public static Map<String, String> GetAllProperties(String filename) { Map<String, String> map = new HashMap<String, String>(); try { Properties pps = new Properties(); InputStream in = new BufferedInputStream(new FileInputStream(BASEPATH+filename)); pps.load(in); Enumeration en = pps.propertyNames(); //獲得配置文件的名字
            while(en.hasMoreElements()) { String strKey = (String) en.nextElement(); String strValue = pps.getProperty(strKey); map.put(strKey, strValue); } } catch (IOException e) { // e.printStackTrace();
 } return map; } //寫入Properties信息
    public static void WriteProperties (String filename, String pKey, String pValue) throws IOException { Properties pps = new Properties(); InputStream in = new FileInputStream(BASEPATH+filename); //從輸入流中讀取屬性列表(鍵和元素對)
 pps.load(in); //調用 Hashtable 的方法 put。使用 getProperty 方法提供並行性。 //強制要求爲屬性的鍵和值使用字符串。返回值是 Hashtable 調用 put 的結果。
        OutputStream out = new FileOutputStream(BASEPATH+filename); pps.setProperty(pKey, pValue); //以適合使用 load 方法加載到 Properties 表中的格式, //將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
        pps.store(out, "Update " + pKey + " name"); out.flush(); in.close(); out.close(); } //批量寫入Properties信息
    public static void WritePropertiesBatch (String filename, List<String> list, Map<String,String> map) throws IOException { Properties pps = new Properties(); InputStream in = new FileInputStream(BASEPATH+filename); InputStreamReader inputStreamReader = new InputStreamReader(in,"UTF-8"); //從輸入流中讀取屬性列表(鍵和元素對)
 pps.load(inputStreamReader); OutputStream out = new FileOutputStream(BASEPATH+filename); for(String str : list) { pps.setProperty(str, map.get(str)); } pps.store(out, "Update"); out.flush(); in.close(); out.close(); } }
相關文章
相關標籤/搜索