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();
    }
    }
     
  • 相关阅读:
    WEB学习-CSS行高、字体,链接的美化以及背景
    WEB学习-CSS中Margin塌陷
    Java反射02 : Class对象获取的三种方式和通过反射实例化对象的两种方式
    Java反射01 : 概念、入门示例、用途及注意事项
    对于写Java的博文
    C++ 运算符优先级列表
    android笔记--Intent和IntentFilter详解
    C语言、指针(一)
    switch...case...语句分析(大表跟小表何时产生)
    SourceInsight教程
  • 原文地址:https://www.cnblogs.com/leirenyuan/p/7483529.html
Copyright © 2011-2022 走看看