读写properties文件属性

来源:互联网 发布:江湖婚庆 3.0源码 编辑:程序博客网 时间:2024/06/05 21:54
说明:很多时候都是项目需求推动才会去找一些实现方式,然后草草的就实现了,想想不太对,决定将自己在工作中遇到的问题慢慢的进行总结,为自己也为别人方便。
需求大致如下,有个spriung boot项目的定时器,每天会执行一次,将扫描mongodb中的某一张表中的type为某一类型的数据,定时copy到mysql数据库中,为了效率问题,
需要将上一次扫描的最大id记录到一个单例的类中进行存储,但是,考虑到项目需要重启(不考虑序列化),就需要将该值持久化存储(暂时不考虑使用数据库等),
我有不想把一个id值存储到一个单独的文件当中,于是决定将该值存储到maven项目的properties文件中。若取到该值为初始化值(比如0)就取配置文件中的值。
在网上找了很多读取properties的资料,但是都好像不是很好用。于是:
public class PropertiesUtil implements Serializable{


private final static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class); 
/**
* 序列化标识
*/
private static final long serialVersionUID = 1L;
private static Properties prop = new Properties();
private final static String file = "sysConfig.properties"; 

static{
FileInputStream in = null;
try {
in = new FileInputStream(file);
prop.load(in);
in.close();
} catch (FileNotFoundException e) {
logger.error("read sysConfig.properties : FileNotFoundException!",e);
} catch (IOException e) {
logger.error("read sysConfig.properties : IOException!",e);
}finally {
try {
if(in != null)in.close();
} catch (IOException e) {
logger.error("read sysConfig.properties ,close FileInputStream error!",e);
}
}
}

/**
* 获取属性的当前值
* @param key 
* @return
*/
public static String getProperty(String key){
return prop.getProperty(key);
}

/**
* 将文件加载到内存中,在内存中修改key对应的value值,再将文件保存
* @param key
* @param value
*/
public static void setProper(String key,String value){
FileOutputStream fos = null;
try {
prop.setProperty(key, value);
fos = new FileOutputStream(file);
prop.store(fos, null);
fos.close();

}catch (FileNotFoundException e) {
logger.error("write sysConfig.properties : FileNotFoundException!",e);
} catch (IOException e) {
logger.error("write sysConfig.properties : IOException!",e);
}finally {
try {
if(fos != null)fos.close();
} catch (IOException e) {
logger.error("write sysConfig.properties error!",e);
}
}

}

}
原创粉丝点击