一般情况配置文件有两种,一是:用properties,二是用XML。当配置文件内容之间有关系时用XML,反之,用properties
ServletContext();如果在WobRoot下面,就直接“/dbconfig.properties”
当配置文件在不同的目录下,会有不同读取方式
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);
}
}
如果配置文件在普通类下,那么可以通过类加载器来读。。。。如下所示
public class UserDao {
private static Properties dbconfig = new Properties();
//以下代码虽然可以读取文件的数据,但是无法获取更新后的数据。
static {
try {
InputStream is = UserDao.class.getClassLoader().getResourceAsStream("dbconfig.properties");
Properties prop = new Properties();
prop.load(is);
} catch (Exception e) {
throw new ExceptionInInitializerError();
}
}