property.store()对properties文件进行操作乱码问题解决方案

        最近的一个项目中需要把一个数据存储在properties文件进行随时调用,但是jdk中的property类自带的store方法只能添加,修改key的value值的话会遇到问题,并且之前的那些propertie属性的中文注释会成为乱码.

       查看store()方法的源代码发现其是用bufferwriter写入行的方式实现的,干脆自己写一个适用的修改key的value值的方法得了.

 

store的源码.store调用store0()方法:

public void store(OutputStream out, String comments)
        throws IOException
    {
        store0(new BufferedWriter(new OutputStreamWriter(out, "8859_1")),
               comments,
               true);
    }

    private void store0(BufferedWriter bw, String comments, boolean escUnicode)
        throws IOException
    {
        if (comments != null) {
            writeComments(bw, comments);
        }
        bw.write("#" + new Date().toString());
        bw.newLine();
        synchronized (this) {
            for (Enumeration<?> e = keys(); e.hasMoreElements();) {
                String key = (String)e.nextElement();
                String val = (String)get(key);
                key = saveConvert(key, true, escUnicode);
                /* No need to escape embedded and trailing spaces for value, hence
                 * pass false to flag.
                 */
                val = saveConvert(val, false, escUnicode);
                bw.write(key + "=" + val);
                bw.newLine();
            }
        }
        bw.flush();
    }

我的解决代码如下,其中key是需要改的key,value是修改后的值:

public void updateProperty(String key,String value){
        List<String> arrayList = new ArrayList<>();
        try {
            FileInputStream fis = new FileInputStream("config.properties");
            InputStreamReader inputReader = new InputStreamReader(fis,"utf-8");
            BufferedReader bf = new BufferedReader(inputReader);			// 按行读取字符串
            String str;
            while ((str = bf.readLine()) != null) {

                if (str.indexOf("#")==-1&&str.indexOf(key+"=")!=-1){
                    arrayList.add(key+"="+value);
                }else{
                    arrayList.add(str);
                }
            }
            FileOutputStream fos = new FileOutputStream("config.properties");
            OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
            BufferedWriter bw = new BufferedWriter(osw);
            for (int i =0;i<arrayList.size();i++){
                bw.write(arrayList.get(i));
                bw.newLine();
            }
            bw.close();
            osw.close();
            fos.close();
            bf.close();
            inputReader.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
  
        }    
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值