简单的属性文件读写工具类

package com.defshare.foundation.global;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.URLUtil;

/**
 * 属性文件读写工具类
 * @author jiangtong
 *
 */
public class PropertiesUtil {
	
	/**
	 * <h3>加载属性文件[不支持缓存]</h3>
	 * @param filename
	 * @return
	 */
	public static Properties loadProperties(String filename){
		Properties properties = new Properties();
		FileInputStream fis = null;
		try {			
			fis = new FileInputStream(new File(URLDecoder.decode(PropertiesUtil.class.getResource("/"+filename).getFile(),"UTF-8")));
			properties.load(fis);			
			return properties;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				if (fis!=null) fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return properties;
	}
	
	/**
	 * <h3>获得属性文件的某个key值,支持缓存
	 * @param filename
	 * @param key
	 * @return
	 */
	public static String get(String filename,String key){		
		ResourceBundle res = ResourceBundle.getBundle(filename.replace(".properties",""));
		String value = res.getString(key);
		res.clearCache();
		return value;
	}
	
	/**
	 * <h3>给属性文件添加或者覆盖键值对</h3>
	 * @param filename
	 * @param key
	 * @param value
	 */
	public static void set(String filename,String key,String value){
		FileWriter fis = null;
		try {
			Properties properties = loadProperties(filename);
			properties.setProperty(key, value);	
			
			fis = new FileWriter(URLDecoder.decode(PropertiesUtil.class.getResource("/").getPath(),"UTF-8")+filename,false);
			properties.store(fis,"");			
			properties.clear();
			fis.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fis!=null)
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值