javaweb 读取properties配置文件参数

雨燕双飞 提交于 2019-12-30 02:20:16

场景1:在servlet中读取properties配置文件参数

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //通过getServletContext来得到流数据
    InputStream properties = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
    Properties props = new Properties();
    props.load(properties);

    String user = props.getProperty("username");
    String pass = props.getProperty("password");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //通过getServletContext来得到文件绝对路径,再用平时读文件的方式得到流数据
    String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
    File file = new File(path);
    FileInputStream in = new FileInputStream(file);

    Properties props = new Properties();
    props.load(properties);

    String user = props.getProperty("username");
    String pass = props.getProperty("password");
}

场景2:不在servlet中,在普通java文件中读取properties配置文件参数

package javaTest;

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

public class testProperties {
    
    public static Properties config(){
        Properties properties = new Properties();
                //通过类装载器得到流数据
        InputStream inputStream = testProperties.class.getClassLoader().getResourceAsStream("jdbc.properties");
        
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return properties;
    }

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!