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();
            }
        }
  • 相关阅读:
    SignalR2结合ujtopo实现拓扑图动态变化
    SignalR2简易数据看板演示
    使用SignalR 2进行服务器广播
    使用SignalR实时Web应用程序
    ZooKeeper安装
    MongoDB安装
    线程安全与非线程安全
    监听器,事件对象,事件源
    Graphics与Canvas
    JDialog
  • 原文地址:https://www.cnblogs.com/mada0/p/4778514.html
Copyright © 2011-2022 走看看