• Properties文件读写问题


    项目需要在Properties配置文件中设置一些配置属性,其中包含一些中文属性。经过一上午的奋斗终于圆满解决问题。

    读取Properties文件所有属性

    Map<String, String> strings = new HashMap<>();

    Properties pros = new Properties();
    InputStream is=PropertiesContoller.class.getClassLoader().getResourceAsStream(
    "sysConfig.properties");//获取到根目录下的Properties资源文件
    pros.load(is);
    Iterator<String> it = pros.stringPropertyNames().iterator();
    while (it.hasNext()) {
    String key = it.next();
    String value = new String(pros.getProperty(key).getBytes("ISO-8859-1"), "gbk");//因为资源文件中存在着中文值,所以要用这种编码方式给他转码,不然会产生乱码
    strings.put(key, value);
    }
    is.close();
    修改Properties文件属性
    URL fileUrl = PropertiesContoller.class.getClassLoader().getResource("sysConfig.properties");//得到文件路径
    OutputStreamWriter fos = null;//OutputStreamWriter可以进行转码,这样就可以在properties文件中存中文的键值,不然存储的是转码后的中文
    Properties pro=new Properties();
    try {
    Properties pros = new Properties();
    InputStream is=PropertiesContoller.class.getClassLoader().getResourceAsStream(
    "sysConfig.properties");
    pros.load(is);
    Iterator<String> it = pros.stringPropertyNames().iterator();
    while (it.hasNext()) {
    String k = it.next();
    String v = new String(pros.getProperty(k).getBytes("ISO-8859-1"), "gbk");
    if(k.equals(key)){
    pro.put(k,value);
    }else {
    pro.put(k,v);
    }
    }
    is.close();
    fos =new OutputStreamWriter( new FileOutputStream(new File(fileUrl.toURI())));
    pro.store(fos,null);
       //存之前一定要先读后写,资源文件中原有的配置会被存储的属性覆盖掉

    ajaxJson.setSuccess(true);
    } catch (URISyntaxException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }finally {
    try {
    fos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
     
  • 相关阅读:
    J2SE基础:7.系统经常使用类一
    Win7 64位 php-5.5.13+Apache 2.4.9+mysql-5.6.19 配置
    FUDCon
    扬帆起航 彼岸花开——2013届毕业晚会《再见民大》倾情再演
    毛磊
    查经
    H.O.T candy
    svn rm --keep-local ./QueryParser_kill.logs
    python datetime笔记
    柯震东_百度百科
  • 原文地址:https://www.cnblogs.com/leirenyuan/p/7483529.html
Copyright © 2020-2023  润新知