jdbc获取properties内容的方式

本文介绍如何在Java中读取Properties配置文件,包括通过字节流、Thread和反射三种方式,并展示了如何加载数据库连接所需的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

properties是java中的一种配置文件,文件的内容是键-值的形式(key-value)。为了在java代码中使数据库的配置文件和代码分开,properties被引用了。文件名为:*.properties的形式。

在eclipse中经常新建一个sources文件,将其放入:

properties中我们主要放置jdbc的 四大参数:

我们只需要在java代码中读取文件中的参数值,从此java代码与数据库配置信息分开了。本文主要关注怎么读取properties。

方法一:通过字节流读取:

private static Properties properties = new Properties();
    static {

        try {
            InputStream in = new FileInputStream("sourses/db.properties");
            properties.load(in);
            Class.forName(properties.getProperty("driver"));
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }

    }

方法二:通过Thread来读取

private static Properties properties = new Properties();
    static {

        try {
            //InputStream in = new FileInputStream("sourses/db.properties");
            InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
            properties.load(in);
            Class.forName(properties.getProperty("driver"));
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }

    }

方法三:通过反射读取

private static Properties properties = new Properties();
    static {

        try {
            //InputStream in = new FileInputStream("sourses/db.properties");
            //InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
            InputStream in=JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(in);
            Class.forName(properties.getProperty("driver"));
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值