zoukankan      html  css  js  c++  java
  • javaweb 读取properties配置文件参数

    场景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;
        }
    
    }
  • 相关阅读:
    ZOJ2334 Monkey King 并查集 STL
    ZOJ2286 Sum of Divisors 筛选式打表
    ZOJ2105 终于找到错误
    ZOJ-2091-Mean of Subsequence (反证法的运用!!)
    【9929】潜水员
    【9928】混合背包
    【t077】宝物筛选
    【9927】庆功会
    【9926】完全背包
    【9925】0/1背包
  • 原文地址:https://www.cnblogs.com/chendc/p/9121888.html
Copyright © 2011-2022 走看看