Java开发中,经常需要在maven工程中读取src/main/resources下的配置文件:
思路如下:
- Class.getClassLoader() 返回类加载器ClassLoader,进而可以获取到classpath路径下的资源
- ClassLoader.getSystemResourceAsStream() 返回读取指定资源的输入流InputStream
- Properties.load(InputStream inStream) 从输入流InputStream中读取属性列表(键和元素对)
// 步骤1:返回类加载器 ClassLoader classLoader = Test.class.getClassLoader(); // 下面3行代码表示通过ClassLoader可以获取到classpath路径 URL resource = classLoader.getResource("test.xml"); String path = resource.getPath(); System.out.println(path); // 步骤2:返回读取指定资源的输入流 InputStream resourceAsStream = classLoader.getResourceAsStream("test.xml"); // 步骤3:从输入流读取属性 Properties properties = new Properties(); properties.load(resourceAsStream);
附:配置文件读取工具类
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PropertiesUtil { private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class); private static Map<String, PropertiesUtil> propsMap; Properties properties; public static synchronized PropertiesUtil getInstance(String propName) { PropertiesUtil instance = null; if (propsMap == null) { propsMap = new HashMap<String, PropertiesUtil>(); } instance = propsMap.get(propName); if (instance == null) { instance = new PropertiesUtil(propName); propsMap.put(propName, instance); } return instance; } private PropertiesUtil(String propName) { ClassLoader classLoader = PropertiesUtil.class.getClassLoader(); InputStream inStream = classLoader.getResourceAsStream(propName); properties = new Properties(); try { properties.load(inStream); } catch (IOException e) { throw new RuntimeException("There's no resource file named [" + propName + "]", e); } } public String getProperty(String key) { return properties.getProperty(key); } public String getProperty(String key, String defaultValue) { return properties.getProperty(key, defaultValue); } public int getInt(String key) { return Integer.valueOf(getProperty(key)); } public int getInt(String key, int defaultValue) { return getProperty(key) == null ? defaultValue : Integer.valueOf(getProperty(key)); } public long getLong(String key) { return Long.valueOf(getProperty(key)); } public long getLong(String key, long defaultValue) { return getProperty(key) == null ? defaultValue : Long.valueOf(getProperty(key)); } public boolean getBoolean(String key) { return Boolean.parseBoolean(getProperty(key)); } public boolean getBoolean(String key, boolean defaultValue) { return getProperty(key) == null ? defaultValue : Boolean.parseBoolean(getProperty(key)); } public Properties getProperties() { return properties; } public static void main(String[] args) { PropertiesUtil pUtil = PropertiesUtil.getInstance("otter.properties"); String reString = pUtil.getProperty("otter.cache.zkhost"); logger.info(reString); } }