web应用获取配置文件
一般情况配置文件有两种,一是:用properties,二是用XML。当配置文件内容之间有关系时用XML,反之,用properties
ServletContext();如果在WobRoot下面,就直接“/dbconfig.properties”
当配置文件在不同的目录下,会有不同读取方式
[java][/java] view plaincopyprint?
- <pre class=”java” name=”code”>package com.heng.test;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Properties;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class Test extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- test3();
- }
- //通过servletContext的getRealPath得到资源的绝对路径后,再通过传统方式读取(好处是可以获取资源的名称,应用在下载文件时)
- private void test3() throws IOException {
- String path = this.getServletContext().getRealPath(“/WEB-INF/classes/dbconfig.properties”);
- String filename = path.substring(path.lastIndexOf(“\\”)+1);
- System.out.println(“当前读取到的资源名称是:”+filename);
- FileInputStream fis = new FileInputStream(path);
- Properties prop = new Properties();
- prop.load(fis);
- String url = prop.getProperty(“url”);
- String usern = prop.getProperty(“username”);
- String pwd = prop.getProperty(“password”);
- System.out.println(url);
- System.out.println(usern);
- System.out.println(pwd);
- }
- //配置文件在WebRoot下面时
- private void test2() throws IOException {
- InputStream is = this.getServletContext().getResourceAsStream(“/dbconfig.properties”);
- Properties prop = new Properties();
- prop.load(is);
- String url = prop.getProperty(“url”);
- String usern = prop.getProperty(“username”);
- String pwd = prop.getProperty(“password”);
- System.out.println(url);
- System.out.println(usern);
- System.out.println(pwd);
- }
- //配置文件在src下面时
- private void test1() throws IOException {
- InputStream is = this.getServletContext().getResourceAsStream(“/WEB-INF/classes/dbconfig.properties”);
- Properties prop = new Properties();
- prop.load(is);
- String url = prop.getProperty(“url”);
- String usern = prop.getProperty(“username”);
- String pwd = prop.getProperty(“password”);
- System.out.println(url);
- System.out.println(usern);
- System.out.println(pwd);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- </pre><br>