技术文章分类(180)

技术随笔(11)

java读取properties文件数据

要注意的是目录,一定是对应服务器里面properties相对你现在要读取这个文件的位置。

 

java读取(调用readProperties()就可以看到效果:

方法一:

package com.test;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadProperties {

    public void readProperties() throws IOException{
        String path = ReadProperties.class.getClassLoader().getResource("db.properties").getPath();
        InputStream in = new FileInputStream(path);
        Properties properties = new Properties();
        properties.load(in);
        String url = properties.getProperty("url");
        System.out.println(url);
    }

}

 

方法二(如果数据更新,无法及时获取更新后的数据)

package com.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadProperties {

    public void readProperties() throws IOException{
        InputStream in = ReadProperties.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(in);
        String url = properties.getProperty("url");
        System.out.println(url);
    }

}

 

 方法三

servlet读取(这里只截取部分代码):

     InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties properties = new Properties();
        properties.load(in);
        String url = properties.getProperty("url");
        String username = properties.getProperty("username");

 

posted @ 2014-06-02 14:37  坤哥MartinLi  阅读(178)  评论(0编辑  收藏  举报