在servlet中读取配置文件的几种方式

     String path = ServletDemo1.class.getClassLoader().getResource("db.properties").getPath();
        //在servlet下,用ServletContext的getRealPath方法的得到资源库路径
        path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
        //在servlet下,用ServletContext的getResource方法的得到资源库路径
        URL url  = this.getServletContext().getResource("/WEB-INF/classes/db.properties");
        path = url.getFile();
        //根据文件路径,得到流
        InputStream is = new FileInputStream(path);
        //在servlet下,用ServletContext的getResourceAsStream方法的直接拿到文件读取流
        is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        //Properties操作文件
        Properties pro = new Properties();
        pro.load(is);
        System.out.println(pro.getProperty("username"));
        pro.put("ccc", "333");
        OutputStream out = new FileOutputStream(path);
        pro.store(out, "comments");

 

posted @ 2015-02-10 14:11  一路向北中  阅读(278)  评论(0)    收藏  举报