web应用获取配置文件

一般情况配置文件有两种,一是:用properties,二是用XML。当配置文件内容之间有关系时用XML,反之,用properties

 

ServletContext();如果在WobRoot下面,就直接“/dbconfig.properties”

当配置文件在不同的目录下,会有不同读取方式

[java][/java] view plaincopyprint?

  1. <pre class=”java” name=”code”>package com.heng.test;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.Properties;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. public class Test extends HttpServlet {
  11.     public void doGet(HttpServletRequest request, HttpServletResponse response)
  12.             throws ServletException, IOException {
  13.         test3();
  14.     }
  15.     //通过servletContext的getRealPath得到资源的绝对路径后,再通过传统方式读取(好处是可以获取资源的名称,应用在下载文件时)
  16.     private void test3() throws IOException {
  17.         String path = this.getServletContext().getRealPath(“/WEB-INF/classes/dbconfig.properties”);
  18.         String filename = path.substring(path.lastIndexOf(“\\”)+1);
  19.         System.out.println(“当前读取到的资源名称是:”+filename);
  20.         FileInputStream fis = new FileInputStream(path);
  21.         Properties prop = new Properties();
  22.         prop.load(fis);
  23.         String url = prop.getProperty(“url”);
  24.         String usern = prop.getProperty(“username”);
  25.         String pwd = prop.getProperty(“password”);
  26.         System.out.println(url);
  27.         System.out.println(usern);
  28.         System.out.println(pwd);
  29.     }
  30.     //配置文件在WebRoot下面时
  31.     private void test2() throws IOException {
  32.         InputStream is = this.getServletContext().getResourceAsStream(“/dbconfig.properties”);
  33.         Properties prop = new Properties();
  34.         prop.load(is);
  35.         String url = prop.getProperty(“url”);
  36.         String usern = prop.getProperty(“username”);
  37.         String pwd = prop.getProperty(“password”);
  38.         System.out.println(url);
  39.         System.out.println(usern);
  40.         System.out.println(pwd);
  41.     }
  42.     //配置文件在src下面时
  43.     private void test1() throws IOException {
  44.         InputStream is = this.getServletContext().getResourceAsStream(“/WEB-INF/classes/dbconfig.properties”);
  45.         Properties prop = new Properties();
  46.         prop.load(is);
  47.         String url = prop.getProperty(“url”);
  48.         String usern = prop.getProperty(“username”);
  49.         String pwd = prop.getProperty(“password”);
  50.         System.out.println(url);
  51.         System.out.println(usern);
  52.         System.out.println(pwd);
  53.     }
  54.     public void doPost(HttpServletRequest request, HttpServletResponse response)
  55.             throws ServletException, IOException {
  56.         this.doGet(request, response);
  57.     }
  58. }
  59. </pre><br>

标签