web工程加载配置文件

1、在servlet中资源文件的读取

    方法一:获取资源文件的数据流

  1. ServletContext context = this.getServletContext();  
  2. InputStream is = context.getResourceAsStream("/config.properties");  
  3. Properties pt = new Properties();  
  4. pt.load(is);  
  5. System.out.println(pt.getProperty("server")); 


       方法二:获取资源文件的绝对路劲,然后利用FileInputStream,与上面的区别在于这里可以获得要操作文件的文件名

[java]  view plain  copy
 print ?
  1. ServletContext context = this.getServletContext();  
  2. String realpath = context.getRealPath("WEB-INF/classes/config.properties");  
  3. System.out.println(realpath);  
  4. String filename = realpath.substring(realpath.lastIndexOf("\\")+1);  
  5. System.out.println(filename);  
  6.   
  7. FileInputStream fis = new FileInputStream(realpath);  
  8.   
  9. Properties pt = new Properties();  
  10. pt.load(fis);  
  11. System.out.println(pt.getProperty("server"));  

在普通类中获取资源配置文件,因为普通类里面没有ServletContext对象,所以要利用类加载器

[java]  view plain  copy
 print ?
  1. URL url = PersonDao.class.getClassLoader().getResource("com/servlet/config.properties");  
  2. String filepath = url.getPath();  
  3. System.out.println(filepath);  
  4.   
  5. FileInputStream fis = new FileInputStream(filepath);  
  6. Properties pt = new Properties();  
  7. pt.load(fis);  
  8. System.out.println(pt.getProperty("server"));  
  9. System.out.println(pt.getProperty("timeout"));  


  1. // 配置文件路径  
  2. public static final String CONFIGPATH = "config.properties";  
  3. // 属性文件   
  4. public static final Properties prop = new Properties();  
  5. // 获取当前类加载的根目录,如:/C:/Program Files/Apache/Tomcat 6.0/webapps/fee/WEB-INF/classes/  
  6. String path = UriFilter.class.getClassLoader().getResource("").toURI().getPath();    
  7. // 把文件读入文件输入流,存入内存中  
  8. FileInputStream fis = new FileInputStream(new File(path + CONFIGPATH ));     
  9. //加载文件流的属性     
  10. prop.load(fis);  

猜你喜欢

转载自blog.csdn.net/rainbow236/article/details/76569562
今日推荐