java修改配置文件
1、项目java代码路径
String filePath = null;
filePath = file.getCanonicalPath();
path = filePath+"/src/main/resources/filter-ip.properties";
2、运行过程中class路径
String path = MyNetcatUdpSource.class.getClassLoader().getResource("filter-ip.properties").getPath();
修改配置文件方法:
FileOutputStream fos = null;
FileInputStream fis = null;
Properties prop = new Properties();
//获取java配置文件路径
String filePath = null;
File file = new File("");
try {
filePath = file.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
String javaPath = filePath+"/src/main/resources/filter-ip.properties";
//获取运行中class配置文件路径
String classPath = MyNetcatUdpSource.class.getClassLoader().getResource("filter-ip.properties").getPath(); //class配置文件路径
try {
fis = new FileInputStream(classPath);
prop.load(fis);// 将属性文件流装载到Properties对象中
prop.setProperty("test","new value");
fos = new FileOutputStream(javaPath);
prop.store(fos, "update ips value");
fos = new FileOutputStream(classPath);
prop.store(fos, "update ips value");
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fos!=null){
fos.close();
}
if (fis!=null){
fis.close();
}
}catch (Exception ex){
ex.printStackTrace();
}
}