A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 郝强勇 中级黑马   /  2013-3-1 14:28  /  848 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

    下面的代码是客户端在访问servlet时,在servlet中调用数据库操作层UserDao对象中的update方法,haha.properties资源文件在src中,也就是在web应用的WEB-INF/classes目录下,但是在访问servlet时,会抛出java.io.FileNotFoundException: C:\Program%20Files\Apache%20Software%20Foundation\Tomcat%206.0\webapps\haohao3\WEB-INF\classes\haha.properties (系统找不到指定的路径。)这个异常。

public void update() throws IOException {
                //通过类加载器得到资源文件的路径
                String path = UserDao.class.getClassLoader().getResource("haha.properties").getPath();
                //通过普通的读取流读取到properties集合中
                FileInputStream fis = new FileInputStream(path);
                Properties dbconfig = new Properties();
                dbconfig.load(fis);
                //获取properties集合中的url数据
                String url = dbconfig.getProperty("url");
                System.out.println(url);
        }

如果通过下面这种方式就没有问题:

public class UserDao {
        private static Properties dbconfig = new Properties();
        static{
                //通过类加载器得到.properties资源数据的流对象
                InputStream in = UserDao.class.getClassLoader().getResourceAsStream("haha.properties");
                try {
                        //将读取流加载到properties集合中
                        dbconfig.load(in);
                } catch (IOException e) {
                        //抛出Error
                        throw new ExceptionInInitializerError(e);
                }
        }
        public void update() {
                String url = dbconfig.getProperty("url");
                System.out.println(url);
        }

评分

参与人数 1技术分 +1 收起 理由
陈丽莉 + 1

查看全部评分

1 个回复

倒序浏览
值得学习ing!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马