首页 / 操作系统 / Linux / Java读取WEB-INF目录下的properties配置文件
如何在Java代码中读取WEB-INF目录下的properties配置文件,下文给出了一个解决方案。我们习惯将一些配置信息写在配置文件中,比如将数据库的配置信息URL、User和Password写在配置文件中,这样部署系统的时候,不需要修改代码,而只需要修改配置文件即可。我将配置文件放在MyEClipse工程文件夹下的WEB-INF目录,在Java代码中读取配置文件的代码是这样的:String path = ParametersReader.class.getResource("/").getPath();
String websiteURL = (path.replace("/build/classes", "").replace("%20"," ").replace("classes/", "") + "parameter.properties").replaceFirst("/", "");第一行代码中的ParametersReader.class指的是当前类的名字,path变量中存放的实际上是当前类所在的路径。这样的话,我们就得到了当前项目WEB-INF的目录。我们将数据库的配置信息写在parameter.properties文件中,这个文件是放在WEB-INF目录下的,该配置文件中的内容如下:#JDBC MySQL Connection
mysql_url=jdbc:mysql://127.0.0.1:3306/mydatabasename
mysql_user=root
mysql_password=123456那么针对上述配置文件,读取该配置文件的完整代码应该是这样的:public static void getParameters() {
String path = ParametersReader.class.getResource("/").getPath();
String websiteURL = (path.replace("/build/classes", "").replace("%20"," ").replace("classes/", "") + "parameter.properties").replaceFirst("/", "");
Properties properties = new Properties();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(websiteURL);
properties.load(fileInputStream);
MYSQL_URL = properties.getProperty("mysql_url");
MYSQL_USER = properties.getProperty("mysql_user");
MYSQL_PASSWORD = properties.getProperty("mysql_password");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}代码中的MYSQL_URL,MYSQL_USER,MYSQL_PASSWORD这三个变量都是定义好的静态变量,getParameters()方法是用来给这三个变量赋值的。目前越来越多使用XML文件代替properties文件来存放配置信息,所以,我们也可以将xml文件放在WEB-INF目录下,通过dom4j等工具来读取xml文件。推荐阅读:Java之properties配置文件介绍附源码 http://www.linuxidc.com/Linux/2013-03/81606.htmJava读取配置properties文件 http://www.linuxidc.com/Linux/2012-09/69775.htm将properties文件放在Jar包并读取 http://www.linuxidc.com/Linux/2012-06/64011.htmJava读写properties文件 http://www.linuxidc.com/Linux/2011-11/46607.htmJava读取properties配置文件 http://www.linuxidc.com/Linux/2011-08/40695.htmJava 加载properties文件的几种方法 http://www.linuxidc.com/Linux/2011-01/31346.htm