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加载配置文件
        // 项目目录: web3\WEB-INF\classes
        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();
        }
    }

 

转载于:https://www.cnblogs.com/mada0/p/4778514.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值