1、在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"));
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"));