package com.zqgame.common.utils;
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.util.Properties;
/**
* @author anquan
* @desc 读写配置文件.<br>
* @date 2015-3-10 下午02:30:59
*/
public class PropertyUtil {
private static Properties props = null;
private static String props_url = "config/adms.properties";
/**
* 读配置文件(默认路径)属性值
* @param pro_name -- 属性名
* @return
*/
public static String getProperty(String pro_name){
try {
props = new Properties();
InputStream in = PropertyUtil.class.getClassLoader().getResourceAsStream(props_url);
props.load(in); ///加载属性列表
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return props.getProperty(pro_name);
}
/**
* 写入配置文件(默认路径)属性值
* @param map
*/
public static void setProperty(String k, String v){
//获取绝对路径
String filePath = PropertyUtil.class.getResource("/" + props_url).getPath();
props = new Properties();
try {
File file = new File(filePath);
if (!file.exists())
file.createNewFile();
InputStream fis = new FileInputStream(file);
props.load(fis);
//一定要在修改值之前关闭fis
fis.close();
OutputStream fos = new FileOutputStream(filePath);
props.setProperty(k, v);
props.store(fos, "update ‘" + v + "‘ value");
//保存,并加入注释
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 指定配置文件读取
* @param properties
* @param pro_name
* @return
*/
public static String getProperty(String properties, String pro_name){
props_url = properties;
return getProperty(pro_name);
}
/**
* 指定配置文件写入
* @param properties
* @param k
* @param v
*/
public static void setProperty(String properties, String k, String v){
props_url = properties;
setProperty(k, v);
}
public static void main(String[] args) {
//取值
System.out.println("pwd="+PropertyUtil.getProperty("password"));
//赋值
PropertyUtil.setProperty("phone","18123672594");
System.out.println("phone="+PropertyUtil.getProperty("phone"));
}
}