前言:
properties文件是我们最为常见的一种配置文件,我们在开发系统时会把一些系统配置信息写在properties配置文件中,比如常见的有数据库连接字符串,端口号信息等。把配置信息写在配置文件后,我们就需要在系统中读取这些配置文件中配置的值,那JAVA该如何读取properties配置文件中的值呢?好了,看如下这段代码吧:
JAVA读取properties配置属性值的代码如下:
package com.daqi.core.utils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * 读取Properties综合类,默认绑定到classpath下的config.properties文件。 * @ 堆代码 duidaima.com */ public class PropertiesUtil { //配置文件的路径 private String configPath=null; /** * 配置文件对象 */ private static Properties props=null; /** * 默认构造函数,用于sh运行,自动找到classpath下的config.properties。 */ static{ InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("source/Source.properties"); props = new Properties(); try { props.load(in); } catch (IOException e) { e.printStackTrace(); } //关闭资源 try { in.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 根据key值读取配置的值 * @author ssq * @param key key值 * @return key 键对应的值 * @throws IOException */ public static String readValue(String key) throws IOException { return props.getProperty(key); } /** * 读取properties的全部信息 * @堆代码 duidaima.com * @throws FileNotFoundException 配置文件没有找到 * @throws IOException 关闭资源文件,或者加载配置文件错误 * */ public static Map<String,String> readAllProperties() throws FileNotFoundException,IOException { //保存所有的键值 Map<String,String> map=new HashMap<String,String>(); @SuppressWarnings("rawtypes") Enumeration en = props.propertyNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); String Property = props.getProperty(key); map.put(key, Property); } return map; } }
总结:
以上就是我们JAVA读取properties配置文件内容的常用方法汇总,这个读取配置文件的辅助类可以在我们需要读取properties属性值的地方直接调用,非常方便。