Java Web项目如何读取.properties配置文件

时间:2022-03-15 18:45:15

在幼儿园管理系统中,为了实现在线预览功能,就使用OpenOffice+SwfTools+Flexpaper技术,在使用的时候,代码里面要配置工具的安装路径(绝对路径),为了方便后期维护该路径。现将该相对应的路径和端口等信息写在配置文件里面。在代码中直接取就行了。

当修改路径的时候,只需要更改一下.properties配置文件,代码里面的都不用改,方便快捷。

在java web项目中src下创建.properties配置文件。

OnlinePreviewConfig.properties配置文件如下:

swftools.url=d:/swftools-0.9.1/pdf2swf.exe
port=8100

读取配置文件类GetProperty.java代码如下:

package com.util.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class GetProperty {

public GetProperty() {
super();
}

// 方法一:通过java.util.ResourceBundle读取资源属性文件
public static String getPropertyByName(String path, String name) {
String result = "";

try {
// 方法一:通过java.util.ResourceBundle读取资源属性文件
result = java.util.ResourceBundle.getBundle(path).getString(name);
System.out.println("name:" + result);
} catch (Exception e) {
System.out.println("getPropertyByName2 error:" + name);
}
return result;
}

// 方法二:通过类加载目录getClassLoader()加载属性文件
public static String getPropertyByName2(String path, String name) {
String result = "";

// 方法二:通过类加载目录getClassLoader()加载属性文件
InputStream in = GetProperty.class.getClassLoader()
.getResourceAsStream(path);
// InputStream in =
// this.getClass().getClassLoader().getResourceAsStream("mailServer.properties");

// 注:Object.class.getResourceAsStream在action中调用报错,在普通java工程中可用
// InputStream in =
// Object.class.getResourceAsStream("/mailServer.properties");
Properties prop = new Properties();
try {
prop.load(in);
result = prop.getProperty(name).trim();
System.out.println("name:" + result);
} catch (IOException e) {
System.out.println("读取配置文件出错");
e.printStackTrace();
}
return result;
}

public static void main(String[] args) {
System.out.println("=="+GetProperty.getPropertyByName("OnlinePreviewConfig","swftools.url"));
System.out.println("==>>"+GetProperty.getPropertyByName2("OnlinePreviewConfig.properties","port"));
}
}
即可完成java web读取.properties配置文件中的值了。