PropertyUtil属性文件读写工具类

/**
 * PropertyUtil属性文件读写工具类
 */
public class PropertyUtil {

	/**
	 * 指定property文件
	 */
	public static final String PROPERTY_FILE =WindowsUtil.getOSName().equals("Windows XP")? "c:/windows/config.properties":"d:\\config.properties";
	public static final String LOG_FILE = "c:/windows/EcollectLog.properties";

	/**
	 * 根据Key 读取Value
	 * 
	 * @param key
	 * @return
	 */
	public static String readData(String key) {
		Properties props = new Properties();
		try {
			InputStream in = new BufferedInputStream(new FileInputStream(
					PROPERTY_FILE));
			props.load(in);
			in.close();
			String value = props.getProperty(key);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	
	/**
	 * 修改或添加键值对 如果key存在,修改 反之,添加。
	 * 
	 * @param key
	 * @param value
	 */
	public static void writeData(String key, String value) {
		Properties prop = new Properties();
		try {
			File file = new File(PROPERTY_FILE);
			if (!file.exists())
				file.createNewFile();
			InputStream fis = new FileInputStream(file);
			prop.load(fis);
			fis.close();//一定要在修改值之前关闭fis
			OutputStream fos = new FileOutputStream(PROPERTY_FILE);
			prop.setProperty(key, value);
			prop.store(fos, "Update '" + key + "' value");
			fos.close();
		} catch (IOException e) {
			System.err.println("Visit " + PROPERTY_FILE + " for updating "
					+ value + " value error");
		}
	}
	/**
	 * 获取参数对象
	 * @return
	 */
	public static Parameter getParameterByFile(){
		Parameter p = null;
		File f = new File(PROPERTY_FILE);
		if(f.exists()){
			p = new Parameter();
			p.setIp(readData("ip"));	
			p.setPort(readData("port"));
			p.setLocalFolder(readData("localFolder"));
			p.setLocalFolder2(readData("localFolder2"));
			p.setLocalFolder3(readData("localFolder3"));
			p.setUsername(readData("username"));
			p.setPassword(readData("password"));
		}
		return p;
	}
	public static void main(String[] args) {
		PropertyUtil.writeData("ip", "192.168.1.1");
		PropertyUtil.writeData("port", "21");
		PropertyUtil.writeData("username", "ddb");
		PropertyUtil.writeData("password", "ddd2");
		PropertyUtil.writeData("localFolder", "d:\\dwg");
		
	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值