java 实时读取、修改properties文件

public class Config {
	
	static String savePath = Config.class.getResource("/config.properties").getPath();  
	// 根据key读取value
	public static String getValue(String key) {
		try {
			//getResourceAsStream 有缓存  修改后 还是返回以前的。。
			//InputStream in = Config.class.getClassLoader().getResourceAsStream("config.properties");
			
			Properties config = new Properties();
			try {
				InputStream in =new BufferedInputStream(new FileInputStream(savePath)); 
				config.load(in);
				in.close();
			} catch (IOException e) {
				System.out.println("加载初始化配置文件失败!");
			}
			String value = config.getProperty(key);
			return value;
		} catch (Exception e) {
			System.err.println("读取初始化配置文件失败!");
			e.printStackTrace();
			return null;
		}
	}
	
    /**
     * 修改文件中的值
     * @param Key 要修改的 key 值
     * @param value 要修改的 key 值对应的 value 值
     */
    public static void setProper(String Key, Object value) {
        Properties pro = new Properties();
        FileInputStream fis = null;
        String path = Config.class.getClassLoader().getResource("config.properties").getFile();
        // 路径中有空格,路径会将空格自动转为 %20,所以把他替换为了空格
        path = path.replace("%20", " ");
        File file = new File(path);
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            pro.load(bis);
            FileOutputStream fos = new FileOutputStream(file);
            pro.setProperty(Key, String.valueOf(value));
            pro.store(fos, null);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值