首页 > Web开发 > 详细

读取web外的配置文件

时间:2015-10-27 15:15:59      阅读:320      评论:0      收藏:0      [点我收藏+]

一般web项目配置文件都放在classPath下面,读取的时候:

1  import java.io.InputStream;
 2 import java.util.Properties;
 3    public class DealConnection {  
 4           private static String url = "";
 5           private static String user = "";
 6           private static String pwd = "";
 7           private static String connStr="";
 8  //构造方法
 9       public DealConnection() {
10           InputStream istr = DealConnection.class.getClassLoader().getResourceAsStream("/parse.properties");//获取classPath下面的配置文件
11           Properties p=new Properties();
12             p.load(istr);
13             istr.close();
14            //获取各个配置的值
15             url=p.getProperty("url").trim();
16             user=p.getProperty("user").trim();
17             pwd=p.getProperty("pwd").trim();
18             connStr=p.getProperty("connStr");
19    }
20 //数据库连接方法
21     public Connection openConn(){
22         Connection conn=null;
23         try {
24             Class.forName(connStr).newInstance();
25             conn = DriverManager.getConnection(url, user, pwd);
26         } catch (Exception e) {
27             e.printStackTrace();
28         }
29         return conn;
30     } 
31 }

现在如果想把配置文件放到外面,让别人也可以方便修改配置文件,假设:配置文件放到tomcat/bin/conf文件下,就修改读取文件那里

public DealConnection() {
        String name=System.getProperty("user.dir");//得到的路径在tomcat/bin路径
        InputStream istr;
        try {
        istr = new FileInputStream(name + "/conf/parse.properties");//读取就是tomcat/bin/conf下的配置文件
        Properties p=new Properties();
            p.load(istr);
            istr.close();
            url=p.getProperty("url").trim();
            user=p.getProperty("user").trim();
            pwd=p.getProperty("pwd").trim();
            connStr=p.getProperty("connStr");
        } catch (Exception e) {
            e.printStackTrace();
        }

applicationContext.xml,在读取classPath配置文件的时候,路径classpath:jdbc.properties

<!-- 属性文件的位置 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>classpath:jdbc.properties</value>
        </property>
    </bean>

 如果要读取tomcat/bin/conf下的配置文件,路径改成:file:conf/jdbc.properties,它是相对于web容器的

<!-- 属性文件的位置 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:conf/jdbc.properties</value>
        </property>
    </bean>

 

读取web外的配置文件

原文:http://www.cnblogs.com/junrong624/p/4914050.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!