关于JavaWeb加载jdbc配置文件与Java项目的不同

方式一:JavaSE项目下

jdbc.properties放在web/jdbc.properties

private static String driverName,url,uname,upwd;
        static {
            try {
                Properties properties= new Properties();
                //直接相对位置
                FileInputStream fis= new FileInputStream(new File("web/jdbc.properties"));
                properties.load(fis);
                //Enumeration<?> enumr =properties.propertyNames();
                //while (enumr.hasMoreElements()){
                //   String key= (String) enumr.nextElement();
                //    String value=properties.getProperty(key);
                //    System.out.println(value);
                String driver=properties.getProperty("driver");
                String url=properties.getProperty("url");
                String uname=properties.getProperty("uname");
                String upwd=properties.getProperty("upwd");
                System.out.println(driver+"-"+url);

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

        }

方式二:JavaWeb项目下

jdbc.properties放在src/jdbc.properties

javaweb项目不能直接用输入流读取相对位置,且位置是web/jdbc.properties,因为运行之后有两个out,一个在tomcat下,一个在工作区下,所以无法区分。

 private static String className,url,name,pwd;
    static {
        try {
            Properties properties= new Properties();
            //获取本类所在的文件夹(src或classes)下的jdbc.properties
            String path=JDBUtil.class.getClassLoader().getResource("jdbc.properties").getPath();
            FileInputStream fis= new FileInputStream(new File(path));
            properties.load(fis);
            //如果jdbc.properties里写的是jdbc.driver,下面参数前均带jdbc.
            className =properties.getProperty("driver");
            url=properties.getProperty("url");
            name=properties.getProperty("username");
            pwd=properties.getProperty("password");
            Class.forName(className);

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

但是经过我的验证:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值