java对properties文件的读写操作

配置文件config.properties

start=2017-01-01
time=7

主处理类:

package hhit.HIVECount.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class ConfigUtil {
	public String str;
	
	/**
	 * 获取资源文件
	 * @throws IOException 
	 */
	public String getConfig(String key) {
		try {
	//一定注意该句,由于配置文件在内存中只加载一次,所以需要每次创建新的对象才能拿到最新的值。一开始我使用第一句话,每次获取的值都是第一次的值
//			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
			FileInputStream inputStream = new FileInputStream("config.properties");
			Properties propertie = new Properties();
			propertie.load(inputStream);
			str = propertie.getProperty(key);
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}

	public void updateConfig(String value)  {
		try {
//			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
			FileInputStream inputStream = new FileInputStream("config.properties");
			Properties propertie = new Properties();
			propertie.load(inputStream);
			System.out.println("===============");
			OutputStream fos = new FileOutputStream("config.properties");
			propertie.setProperty("start", value);
			// 以适合使用 load 方法加载到 Properties 表中的格式,
			// 将此 Properties 表中的属性列表(键和元素对)写入输出流
			propertie.store(fos, "");
			String start = propertie.getProperty("start");
			System.out.println("start:"+start);
			inputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		ConfigUtil cf = new ConfigUtil();
		cf.updateConfig("2017-12-25");
		String str=cf.getConfig("time");
		System.out.println(str);
	}
}

一定注意配置文件的路径,我的配置文件在跟路径下:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值