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();
    }
    }
     
  • 相关阅读:
    log4j2 标签解析
    7.3
    work-7.2
    爬取豆瓣上某个用户标记的想读的或者读过的图书信息
    python爬虫程序打包为exe程序并在控制台下运行
    爬取任意两个用户在豆瓣上标记的想读的图书信息的交集
    解决c# progressBar更新出现界面假死
    数据库死锁(大神请路过)
    Excel的下载和读取,部分代码(大神请路过)
    大数据缓存:redis
  • 原文地址:https://www.cnblogs.com/leirenyuan/p/7483529.html
Copyright © 2011-2022 走看看