1、在servlet中资源文件的读取
方法一:获取资源文件的数据流
- ServletContext context = this.getServletContext();
- InputStream is = context.getResourceAsStream("/config.properties");
- Properties pt = new Properties();
- pt.load(is);
- System.out.println(pt.getProperty("server"));
方法二:获取资源文件的绝对路劲,然后利用FileInputStream,与上面的区别在于这里可以获得要操作文件的文件名
- ServletContext context = this.getServletContext();
- String realpath = context.getRealPath("WEB-INF/classes/config.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("server"));
在普通类中获取资源配置文件,因为普通类里面没有ServletContext对象,所以要利用类加载器
- URL url = PersonDao.class.getClassLoader().getResource("com/servlet/config.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("server"));
- System.out.println(pt.getProperty("timeout"));
-
- public static final String CONFIGPATH = "config.properties";
-
- public static final Properties prop = new Properties();
-
- String path = UriFilter.class.getClassLoader().getResource("").toURI().getPath();
-
- FileInputStream fis = new FileInputStream(new File(path + CONFIGPATH ));
-
- prop.load(fis);