配置文件中内容:
lastModify=2014-08-21
public class TestProperties {
public static Properties properties;
static{
try{
properties=new Properties();
InputStream input=TestProperties.class.getResourceAsStream("info.properties");
properties.load(input);
input.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
String last=getLastModify();
String str=update("2014-09-05");
System.out.println(last);
System.out.println(getLastModify());
}
public static String getLastModify(){
String last= (String) properties.get("lastModify");
return last;
}
public static String update(String lastModify){
try{
FileOutputStream out=new FileOutputStream(new File(TestProperties.class.getResource("info.properties").toURI()));
String str= (String) properties.setProperty("lastModify",lastModify);
properties.store(out, "Update lastModifyTime");
out.close();
return str;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
第一次运行效果:
2014-08-21
2014-09-05
运行结果没有问题
第二次运行结果:
2014-09-05
2014-09-05
也没有问题
但是我现在最大的问题就是,为什么properties文件中的内容没有改变,还是以前的2014-08-21,而不是我修改之后的数据呢?求解呀!
------解决方案--------------------
class.getResource获取的是CLASSPATH路径下的文件
你可以sout看一下,保存的文件不是在工程目录下,所以原文件没有变文件A。
后来保存的文件B是新生成的文件,在classes文件夹下,如果想变成相对于工程路径保存文件就直接new File(文件相对于工程目录)
像
new File("src/main/java/info.properties")
------解决方案--------------------
修改了啊,你再试试看,执行完程序刷新下文件所在的磁盘
#Update lastModifyTime
#Mon Aug 25 13:57:58 GMT+08:00 2014
lastModify=2014-09-05