我想改变.properties里属性的值,但是为啥还是原来的值呢,求高手解答啊
以下是我写的重置值的函数,谢谢
public void setPara(String fileName,String key,String value) {
Properties prop = new Properties();
try{
ClassLoader cl = this.getClass().getClassLoader();
InputStream is = cl.getResourceAsStream(fileName);
prop.load(is);
if(is != null)
is.close();
}catch(Exception e){
System.out.println(e + "file " + fileName + " not found");
}
prop.setProperty(key,value);
FileOutputStream fos;
try {
fos = new FileOutputStream(fileName);
try {
prop.store(fos, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
[最优解释]
你读取的是class目录下的config.properties可是你在set方法里面把它输出到了项目的目录下了
要把那个set方法的
FileOutputStream fos = new FileOutputStream(cl.getResource(fileName).toURI().getPath());改成这样
[其他解释]
public class ReadPro implements Serializable {
public String getPara(String fileName,String field){
Properties prop = new Properties();
try{
ClassLoader cl = this.getClass().getClassLoader();
InputStream is = cl.getResourceAsStream(fileName);
prop.load(is);
if(is != null)
is.close();
}catch(Exception e){
System.out.println(e + "file " + fileName + " not found");
}
return prop.getProperty(field);
}
public void setPara(String fileName,String key,String value) {
Properties prop = new Properties();
try{
ClassLoader cl = this.getClass().getClassLoader();
InputStream is = cl.getResourceAsStream(fileName);
prop.load(is);
if(is != null)
is.close();
}catch(Exception e){
System.out.println(e + "file " + fileName + " not found");
}
prop.setProperty(key,value);
FileOutputStream fos;
try {
fos = new FileOutputStream(fileName);
try {
prop.store(fos,null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String [] args){
ReadPro readpro = new ReadPro();
String ex = readpro.getPara("config.properties", "ExceptionPiont");
System.out.println("++++++++++++++++++++++"+ex);
readpro.setPara("config.properties","ExceptionPiont" , "23");
String exchange = readpro.getPara("config.properties", "ExceptionPiont");
System.out.println("++++++++++++++++++++++"+exchange);
}
}
[其他解释]
什么原因呢?