提示
有时候会需要读取配置文件(.properties),无论是项目内还是项目外,于是从网上收集了一个工具类,进行了一些优化.
请注意:代码基于Jdk 9 编译.
代码
package xyz.suancaiyu.util; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Set; /** * Properties 工具类 * * @Author: puruidong * @Version: 2018/3/15 17:29 */ public class PropertiesUtil { private static final String APPLICATIONFILEPATH = "F:\\conf\\application.properties"; private PropertiesUtil() { } private static PropertiesUtil propertiesUtil = null; public static PropertiesUtil getInstance() { if (propertiesUtil == null) { propertiesUtil = new PropertiesUtil(); } return propertiesUtil; } /** * 根据文件名获取Properties对象 * <p> * <p> * 读取项目内部配置文件: * <p> * <p> * in = PropertiesUtil.class.getClassLoader().getResourceAsStream(Constats.APPLICATIONFILEPATH); * * @return */ public Properties read() { try(InputStream in = new FileInputStream(new File(APPLICATIONFILEPATH))) { Properties prop = new Properties(); if (in == null) { return null; } prop.load(in); return prop; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 根据文件名和键名获取值 * * @param key * @return */ public String readKeyValue(String key) { Properties prop = read(); if (prop != null) { return prop.getProperty(key); } return null; } /** * 根据键名获取值 * * @param prop * @param key * @return */ public String readKeyValue(Properties prop, String key) { if (prop != null) { return prop.getProperty(key); } return null; } /** * 写入 * * @param fileName * @param key * @param value */ public void writeValueByKey(String fileName, String key, String value) { Map<String, String> properties = new HashMap<>(); properties.put(key, value); writeValues(properties); } /** * 写入 * * @param properties */ public void writeValues(Map<String, String> properties) { try(InputStream in =new FileInputStream(new File(APPLICATIONFILEPATH)); OutputStream out = new FileOutputStream(APPLICATIONFILEPATH);) { /* 如果是项目内的配置文件,需要使用下面这一行代码. in = PropertiesUtil.class.getClassLoader().getResourceAsStream(APPLICATIONFILEPATH); */ if (in == null) { throw new RuntimeException("读取的文件(" + APPLICATIONFILEPATH + ")不存在,请确认!"); } Properties prop = new Properties(); prop.load(in); // 项目内部配置文件才用这个. // String path = PropertiesUtil.class.getResource( APPLICATIONFILEPATH).getPath(); if (properties != null) { Set<String> set = properties.keySet(); for (String string : set) { prop.setProperty(string, properties.get(string)); } } prop.store(out, "update properties"); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println(PropertiesUtil.getInstance().readKeyValue("libpath")); Map<String, String> maps = new HashMap<>(2); maps.put("add", "true"); PropertiesUtil.getInstance().writeValues(maps); } }