配置文件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);
}
}
一定注意配置文件的路径,我的配置文件在跟路径下: