Java读取WEB-INF目录下的properties配置文件

时间:2023-12-18 08:40:14

如何在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文件。