可以通过:java.util.Properties类实现配置文件的读取解析成key-value
package utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertyHelper {
private String path;
private static PropertyHelper $instance;
private Properties $properties = new Properties();
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public static boolean containsKey(String key) {
return getInstance().$properties.containsKey(key);
}
public static String get(String key) {
String value = getInstance().$properties.getProperty(key);
return value;
}
public static void set(String key, String value) {
getInstance().$properties.setProperty(key, value);
}
public PropertyHelper() {
path = ("".equals(path) || path == null) ? "/conf.properties" : path;
InputStream inps = getClass().getResourceAsStream(path);
try {
$properties.load(inps);
if (inps != null)
inps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static PropertyHelper getInstance() {
if ($instance == null) {
synchronized (PropertyHelper.class) {
if ($instance == null) {
$instance = new PropertyHelper();
}
}
}
return $instance;
}
}
此时的conf.properties配置文件放到src目录下。发布到tomcat时会默认发布到classes目录下。