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;
        }
    
    }
  • 相关阅读:
    第四章 解决面试题的思路
    第三章 高质量的代码
    第二章 面试需要的基础知识
    第九章 海量数据处理
    第八章 数据结构与算法
    用打王者荣耀的姿势,去做有意义的事【恶魔奶爸】
    linux入门级知识回顾
    Django回顾
    复习爬虫
    django预热
  • 原文地址:https://www.cnblogs.com/chendc/p/9121888.html
Copyright © 2011-2022 走看看