PropertiesConfiguration
PropertiesConfiguration是一个读取Properties配置文件的工具,可以实现快速的读取。
maven依赖的包
<dependency> <groupId>commons-configuration</groupId> <artifactId>commons-configuration</artifactId> <version>1.9</version> </dependency> <!-- commons-configuration 自动加载的是2.1的版本,编译时会报错,所以再加上这个 --> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>
核心代码
PropertiesConfiguration config=new PropertiesConfiguration("config.properties");//构造对象 //默认的编码格式是ISO-8859-1,所以才在读取文件之前先设置了编码格式 propsConfig.setEncoding("UTF-8") config.getStringArray(key); //根据关键字获取String列表 config.getString(key, ""); //根据关键字获取String类型参数propsConfig的默认分割符是',',换句话说,如果使用','分割,使用getString去取的话只能取到','前面的内容。解决方案见下面的代码
String propertiesFileName="config.properties"; PropertiesConfiguration config=new PropertiesConfiguration(); propsConfig.setEncoding("UTF-8") config.setListDelimiter('.');//如果内容中包含,设置分割符以后在加载文件才能保证取到所有内容 propsConfig.load(propertiesFileName);
封装工具
import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; public class PropertiesUtils { private static Configuration config; static { if (null == config) { try { config = new PropertiesConfiguration("config.properties"); } catch (ConfigurationException e) { e.printStackTrace(); } } } private PropertiesUtils() { } public static String getString(String key) { return config.getString(key, ""); } public static String[] getStringArray(String key) { return config.getStringArray(key); } public static void main(String[] args) { String[] strs = getStringArray("mail.touser"); for (String string : strs) { System.out.println(string); } } }