博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
快捷获取Properties中数据
阅读量:4228 次
发布时间:2019-05-26

本文共 2969 字,大约阅读时间需要 9 分钟。

写了一个工具了,可以方便的访问.properties文件中的数据,代码如下

public final class MyProperties {    private final static String[] PATHS = new String[]{"parameter.properties"};    private Map
valueMap; private static volatile MyProperties myProperties; private MyProperties() { init(); } private void init() { Map
currentMap = new HashMap<>(50); Arrays.asList(PATHS).forEach(x -> { try { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(x); if (inputStream == null) { throw new RuntimeException(String.format("路径[%s]下的资源无法找到", x)); } Properties properties = new Properties(); properties.load(new InputStreamReader(inputStream)); int originalSize = currentMap.size(); currentMap.putAll(properties); //校验值冲突 if (originalSize + properties.size() > currentMap.size()) { throw new RuntimeException("存在键冲突"); } } catch (IOException e) { throw new RuntimeException(e); } }); valueMap = currentMap; } /** * 获取字符串 * * @param key * @return */ public String getString(String key) { Object o = valueMap.get(key); return o == null ? null : String.valueOf(o); } /** * 获取字符串否则默认值 * * @param key * @param defaultV * @return */ public String getStringOrDefault(String key, String defaultV) { Object o = valueMap.get(key); return o == null ? defaultV : String.valueOf(o); } /** * 获取integer * * @param key * @return */ public Integer getInteger(String key) { Object o = valueMap.get(key); return o == null ? null : Integer.parseInt(String.valueOf(o)); } /** * 获取integer否则默认值 * * @param key * @param defaultV * @return */ public Integer getIntegerOrDefault(String key, Integer defaultV) { Object o = valueMap.get(key); return o == null ? defaultV : Integer.parseInt(String.valueOf(o)); } /** * 刷新 */ public void refresh() { synchronized (this) { init(); } } /** * 获取对象 * * @return */ public static MyProperties getInstance() { if (myProperties == null) { synchronized (MyProperties.class) { if (myProperties == null) { //这样可以防止对象没有初始化完成就被使用 MyProperties properties = new MyProperties(); myProperties = properties; } } } return myProperties; }}

使用也很简单,如下就可以读取文件中的数据了

public class Main {    public static void main(String[] args) {        System.out.println(MyProperties.getInstance().getString("hello"));        System.out.println(MyProperties.getInstance().getInteger("test"));    }}

转载地址:http://phjqi.baihongyu.com/

你可能感兴趣的文章
PAT_A 1013. Battle Over Cities (25)
查看>>
PAT_A 1015. Reversible Primes (20)
查看>>
SetWindowLong函数介绍
查看>>
百度云cdn,bos设置
查看>>
[chrome]好用的chrome Json 格式化插件
查看>>
[Android]hex 64k解决
查看>>
[iphone]调出来控制的小圆球(控制点)
查看>>
[react-native]prop,state对比
查看>>
ssl问题被google 拒收
查看>>
[GreenDAO]like的坑
查看>>
正则表达式中的元字符
查看>>
Java Collection很好的介绍
查看>>
java中的JSon解析
查看>>
解决 Mybatis Generator由表字段使用关键字导致的异常方案
查看>>
HTTP请求的基础知识——HTTP中GET,POST和PUT的区别
查看>>
为什么需要Java反射?
查看>>
Java代码反编译——下载class字节码文件及反编译.class文件
查看>>
稀疏表示去噪的理解
查看>>
稀疏表示(二)——KSVD算法详解(结合代码和算法思路)
查看>>
剑指Offer习题集锦——Java实现及思路分析
查看>>