且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java Properties类新增、更新及写入文件【解决中文乱码问题】

更新时间:2021-12-23 02:34:08

该方式支持新增及编辑,
如果对应的配置文件中,包含了对应的key,则执行更新;
如果不包含,则执行插入。

Properties pro=new Properties();
//解决读取配置文件,中文乱码问题
InputStream inputStream = PropertiesBean.class.getClassLoader().getResourceAsStream("config.properties");
properties.load(new InputStreamReader(inputStream,"UTF-8"));

//插入或更新对应的属性值
prop.setProperty("key", "value");

String path = Thread.currentThread().getContextClassLoader().getResource(configFileName).getPath();
try (
  //自动关闭的流,解决写入时中文异常的问题
  OutputStreamWriter     output = new OutputStreamWriter(new FileOutputStream(Thread.currentThread().getContextClassLoader().getResource(path).getPath()), "UTF-8");
) {
  prop.store(output , "modify");
  outputFile.flush();
} catch (IOException e) {
  e.printStackTrace();
}