本文共 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/