1、Web工程下读取配置文件的几种常见方式

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"));

在普通类中获取资源配置文件,因为普通类里面没有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"));



你可能感兴趣的:(Web,servlet,利用类加载器来读取配置文件,资源文件的读取)