zoukankan      html  css  js  c++  java
  • Servlet获取web项目中Properties文件

    在web项目中读取Properties文件配置:

    properties文件内容:

    name=tom
    password=12345
    View Code

    1、使用 类名.class.getResourceAsStream()

    private void readPropertiesByClass() {
            // 根目录是class文件所在目录,如果以 /开头从classpath目录中找db.properties;如果不以/开头从当前类所在的包中找
            InputStream inputStream = ReadPropertiesServlet.class
                    .getResourceAsStream("/db.properties");
            Properties properties = new Properties();
            try {
                // 加载
                properties.load(inputStream);
                // getProperty()方法内部调用get()并将返回结果包装成String类型
                String name = properties.getProperty("name");
                System.out.println(name);
                System.out.println(properties.get("name"));// 返回Object类型
                // 失败,因为写入properties文件中的数据是以String类型存储的
                // int i = (int)properties.get("password");
                // System.out.println(i + 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    2、使用ServletContext#getResourceAsStream()

    private void readPropertiesByServletContext() {
            // ServletContext方法读取配置 / 代表WebProject工程名,同级不需'/'
            ServletContext servletContext = getServletContext();
            InputStream inputStream = servletContext.getResourceAsStream("db.properties");
            Properties properties = new Properties();
            try {
                properties.load(inputStream);
                System.out.println(properties.getProperty("name"));
                System.out.println(properties.getProperty("password"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    3.使用ClassLoader加载配置文件

    private void readPropertiesByClassLoader() {
            // 使用ClassLoader加载配置文件
            // 项目目录: web3WEB-INFclasses
            ClassLoader classLoader = ReadPropertiesServlet.class.getClassLoader();
            // 上级目录:../
            InputStream inputStream = classLoader
                    .getResourceAsStream("../../db.properties");
            // 获取Properties实例的两种方法
            // Properties properties = new Properties();
            Properties properties = System.getProperties();
            try {
                properties.load(inputStream);
                System.out.println(properties.getProperty("name"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
  • 相关阅读:
    linux下自动同步internet时间
    String,StringBuffer与StringBuilder的区别
    Spring Boot CLI安装
    java中Date与String的相互转化
    MyBatis Sql语句中的转义字符
    MyBatis详解 与配置MyBatis+Spring+MySql
    MyBatis的foreach语句详解
    不可变集合 Immutable Collections
    Java日期时间使用总结
    Java将一段逗号分割的字符串转换成一个数组
  • 原文地址:https://www.cnblogs.com/mada0/p/4778514.html
Copyright © 2011-2022 走看看