程序员

JSP 中Spring的Resource类读写中文Properties实例代码

作者:admin 2021-04-28 我要评论

JSP 中Spring的Resource类读写中文Properties 摘要: Spring对Properties的读取进行了完善而全面的封装,对于写则仍需配合FileOutputStream进行。 package com.oo...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

JSP 中Spring的Resource类读写中文Properties

摘要: Spring对Properties的读取进行了完善而全面的封装,对于写则仍需配合FileOutputStream进行。

 package com.oolong.common.util;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.*;
import java.util.*;

public class UserVar {
 private static String configFile = "classpath*:param.properties";
 private static org.springframework.core.io.Resource resourceWritable;
 private static Properties p;

 /**
  * 注意事项:
  * 1、properties放在source目录下
  * 2、param.properties至少有一对键值对
  */
 static {
  p = new Properties();
  org.springframework.core.io.Resource[] resources = null;
  try {
   ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
   resources = resolver.getResources(configFile);
   if (resources != null) {
    for (org.springframework.core.io.Resource r : resources) {
     if (r != null) {
      p.load(r.getInputStream());
      resourceWritable = r;
     }
    }
   }
  } catch (IOException e1) {
   e1.printStackTrace();
  }
 }

 public static String get(String key) {
  String v = (String) p.get(key);
  if (v != null) {
   try {
    return new String(v.getBytes("ISO-8859-1"), "GBK");
   } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    return null;
   }
  }
  return null;
 }

 public static void set(String key,String value){
  if (null != resourceWritable) {
   try {
    OutputStream fos = new FileOutputStream(resourceWritable.getFile());
    Properties p = new Properties();
    p.load(resourceWritable.getInputStream());
    value = new String(value.getBytes("GBK"),"ISO-8859-1");
    p.setProperty(key, value);
    p.store(fos, null);
    fos.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}


感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


本文转载自网络,原文链接:https://m.jb51.net/article/109845.htm

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 解密阿里云高效病原体基因检测工具

    解密阿里云高效病原体基因检测工具

  • 探秘!在阿里云做产品经理是怎样的体验

    探秘!在阿里云做产品经理是怎样的体验

  • 精彩回顾 | 阿里云 Serverless Develop

    精彩回顾 | 阿里云 Serverless Develop

  • 为什么SOFA RPC调用30s还不超时?

    为什么SOFA RPC调用30s还不超时?