zoukankan      html  css  js  c++  java
  • 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();
    }
    }
     
  • 相关阅读:
    MVC中单用户登录
    用CheckBox做删除时请不要使用@Html.CheckBoxFor
    MVC3"不允许启动新事务,因为有其他线程正在该会话中运行"错误解决方法
    下拉菜单DropDwon实现方法
    MVC3中Ajax.ActionLink用法
    删除时显示确认对话框
    民航指令学习(一)
    CentOS常用命令
    CentOS手动分区步骤
    CentOS下安装JDK和Tomcat
  • 原文地址:https://www.cnblogs.com/leirenyuan/p/7483529.html
Copyright © 2011-2022 走看看