加载文件

来源:互联网 发布:国外地图导航软件 编辑:程序博客网 时间:2024/06/05 12:29
1、加载 .properties工具类
package util;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * 读db.properties文件 * */public class ConfigUtil {private static Properties props = new Properties();static{/* * ConfigUtil.class : 获得ConfigUtil的class对象。 * ConfigUtil.class.getClassLoader:获得加载 * ConfigUtil的类加载器。 * 类加载器的getResourceAsStream方法: * 会依据指定的路径查找文件,并且 * 返回一个InputStream流。 */<span style="background-color: rgb(255, 255, 0);">InputStream ips  = ConfigUtil.class.getClassLoader().getResourceAsStream("util/db.properties");</span>try {props.load(ips);} catch (IOException e) {e.printStackTrace();System.out.println("读取db.properties文件失败");}}public static String getValue(String key){return props.getProperty(key);}public static void main(String[] args){System.out.println(getValue("driver"));}}
2、加载 <span style="font-family: Arial, Helvetica, sans-serif;">applicationContext.xml,使用spring容器</span>
String conf = "applicationContext.xml";        AbstractApplicationContext ac =            new ClassPathXmlApplicationContext(conf);
   加载配置文件
<!-- context:property-placeholder location="classpath*:*.properties"/-->  <span style="white-space:pre"></span><span style="white-space:pre"></span><bean<span style="white-space:pre"></span>class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="propertyConfigurer"><span style="white-space:pre"></span><property name="locations"><span style="white-space:pre"></span><list><span style="white-space:pre"></span><value>*.properties</value><span style="white-space:pre"></span></list><span style="white-space:pre"></span></property><span style="white-space:pre"></span></bean>


0 0