标签:
servlet中资源文件的读取
方法一:获取资源文件的数据流
ServletContext context = this.getServletContext(); InputStream is = context.getResourceAsStream("/person.properties"); Properties pt = new Properties(); pt.load(is); System.out.println(pt.getProperty("name"));
方法二:获取资源文件的绝对路劲,然后利用FileInputStream,与上面的区别在于这里可以获得要操作文件的文件名
ServletContext context = this.getServletContext(); String realpath = context.getRealPath("WEB-INF/classes/person.properties"); System.out.println(realpath); String filename = realpath.substring(realpath.lastIndexOf("\\")+1); System.out.println(filename); FileInputStream fis = new FileInputStream(realpath); Properties pt = new Properties(); pt.load(fis); System.out.println(pt.getProperty("name"));
在普通类中获取资源配置文件,因为普通类里面没有ServletContext对象,所以要利用类加载器
URL url = PersonDao.class.getClassLoader().getResource("com/baowei/servlet/person.properties"); String filepath = url.getPath(); System.out.println(filepath); FileInputStream fis = new FileInputStream(filepath); Properties pt = new Properties(); pt.load(fis); System.out.println(pt.getProperty("name")); System.out.println(pt.getProperty("age"));
标签:
原文地址:http://www.cnblogs.com/zhangbaowei/p/4671696.html