从 JFinal 框架中,抽取出一个 读取 .properties 配置文件的助手类 PropHelper.java
使用示例:
PropHelper.use("config.txt", "UTF-8");
PropHelper.use("other_config.txt", "UTF-8");
String userName = PropHelper.get("userName");
String password = PropHelper.get("password");
userName = PropHelper.use("other_config.txt").get("userName");
password = PropHelper.use("other_config.txt").get("password");
PropHelper.use("wen/jianbao/config_in_sub_directory_of_classpath.txt");
1、文件 Prop.java
package wen.jianbao.helper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
/**
* Prop. Prop can load properties file from CLASSPATH or File object.
*/
public class Prop {
protected Properties properties;
private static final Logger logger = LoggerFactory.getLogger(Prop.class);
/**
* 支持 new Prop().appendIfExists(...)
*/
public Prop() {
properties = new Properties();
}
/**
* Prop constructor.
*
* @see #Prop(String, String)
*/
public Prop(String fileName) {
this(fileName, "UTF-8");
}
/**
* Prop constructor
* <p>
* Example:<br>
* Prop prop = new Prop("my_config.txt", "UTF-8");<br>
* String userName = prop.get("userName");<br><br>
* <p>
* prop = new Prop("com/dudubashi/file_in_sub_path_of_classpath.txt", "UTF-8");<br>
* String value = prop.get("key");
*
* @param fileName the properties file's name in classpath or the sub directory of classpath
* @param encoding the encoding
*/
public Prop(String fileName, String encoding) {
InputStream inputStream = null;
try {
inputStream = getClassLoader().getResourceAsStream(fileName); // properties.load(Prop.class.getResourceAsStream(fileName));
if (inputStream == null) {
throw new IllegalArgumentException("Properties file not found in classpath: " + fileName);
}
properties = new Properties();
properties.load(new InputStreamReader(inputStream, encoding));
} catch (IOException e) {
throw new RuntimeException("Error loading properties file.", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
private ClassLoader getClassLoader() {
ClassLoader ret = Thread.currentThread().getContextClassLoader();
return ret != null ? ret : getClass().getClassLoader();
}
/**
* Prop constructor.
*
* @see #Prop(File, String)
*/
public Prop(File file) {
this(file, "UTF-8");
}
/**
* Prop constructor
* <p>
* Example:<br>
* Prop prop = new Prop(new File("/var/config/my_config.txt"), "UTF-8");<br>
* String userName = prop.get("userName");
*
* @param file the properties File object
* @param encoding the encoding
*/
public Prop(File file, String encoding) {
if (file == null) {
throw new IllegalArgumentException("File can not be null.");
}
if (!file.isFile()) {
throw new IllegalArgumentException("File not found : " + file.getName());
}
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
properties = new Properties();
properties.load(new InputStreamReader(inputStream, encoding));
} catch (IOException e) {
throw new RuntimeException("Error loading properties file.", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
public Prop append(Prop prop) {
if (prop == null) {
throw new IllegalArgumentException("prop can not be null");
}
properties.putAll(prop.getProperties());
return this;
}
public Prop append(String fileName, String encoding) {
return append(new Prop(fileName, encoding));
}
public Prop append(String fileName) {
return append(fileName, "UTF-8");
}
public Prop appendIfExists(String fileName, String encoding) {
try {
return append(new Prop(fileName, encoding));
} catch (Exception e) {
return this;
}
}
public Prop appendIfExists(String fileName) {
return appendIfExists(fileName, "UTF-8");
}
public Prop append(File file, String encoding) {
return append(new Prop(file, encoding));
}
public Prop append(File file) {
return append(file, "UTF-8");
}
public Prop appendIfExists(File file, String encoding) {
if (file.isFile()) {
append(new Prop(file, encoding));
}
return this;
}
public Prop appendIfExists(File file) {
return appendIfExists(file, "UTF-8");
}
public String get(String key) {
return properties.getProperty(key);
}
public String get(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
public Integer getInt(String key) {
return getInt(key, null);
}
public Integer getInt(String key, Integer defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
return Integer.parseInt(value.trim());
}
return defaultValue;
}
public Long getLong(String key) {
return getLong(key, null);
}
public Long getLong(String key, Long defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
return Long.parseLong(value.trim());
}
return defaultValue;
}
public Boolean getBoolean(String key) {
return getBoolean(key, null);
}
public Boolean getBoolean(String key, Boolean defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
value = value.toLowerCase().trim();
if ("true".equals(value)) {
return true;
} else if ("false".equals(value)) {
return false;
}
throw new RuntimeException("The value can not parse to Boolean : " + value);
}
return defaultValue;
}
public boolean containsKey(String key) {
return properties.containsKey(key);
}
public boolean isEmpty() {
return properties.isEmpty();
}
public boolean notEmpty() {
return !properties.isEmpty();
}
public Properties getProperties() {
return properties;
}
}
2、文件 PropHelper.java
package wen.jianbao.helper;
import java.io.File;
import java.util.concurrent.ConcurrentHashMap;
/**
* PropHelper. PropHelper can load properties file from CLASSPATH or File object.
*/
public class PropHelper {
private static Prop prop = null;
private static final ConcurrentHashMap<String, Prop> map = new ConcurrentHashMap<>();
private PropHelper() {
}
/**
* Use the first found properties file
*/
public static Prop useFirstFound(String... fileNames) {
for (String fn : fileNames) {
try {
return use(fn, "UTF-8");
} catch (Exception e) {
continue;
}
}
throw new IllegalArgumentException("没有配置文件可被使用");
}
/**
* Use the properties file. It will loading the properties file if not loading.
*
* @see #use(String, String)
*/
public static Prop use(String fileName) {
return use(fileName, "UTF-8");
}
/**
* Use the properties file. It will loading the properties file if not loading.
* <p>
* Example:<br>
* PropHelper.use("config.txt", "UTF-8");<br>
* PropHelper.use("other_config.txt", "UTF-8");<br><br>
* String userName = PropHelper.get("userName");<br>
* String password = PropHelper.get("password");<br><br>
* <p>
* userName = PropHelper.use("other_config.txt").get("userName");<br>
* password = PropHelper.use("other_config.txt").get("password");<br><br>
* <p>
* PropHelper.use("com/dudubashi/config_in_sub_directory_of_classpath.txt");
*
* @param fileName the properties file's name in classpath or the sub directory of classpath
* @param encoding the encoding
*/
public static Prop use(String fileName, String encoding) {
Prop result = map.get(fileName);
if (result == null) {
synchronized (PropHelper.class) {
result = map.get(fileName);
if (result == null) {
result = new Prop(fileName, encoding);
map.put(fileName, result);
if (PropHelper.prop == null) {
PropHelper.prop = result;
}
}
}
}
return result;
}
/**
* Use the properties file bye File object. It will loading the properties file if not loading.
*
* @see #use(File, String)
*/
public static Prop use(File file) {
return use(file, "UTF-8");
}
/**
* Use the properties file bye File object. It will loading the properties file if not loading.
* <p>
* Example:<br>
* PropHelper.use(new File("/var/config/my_config.txt"), "UTF-8");<br>
* Strig userName = PropHelper.use("my_config.txt").get("userName");
*
* @param file the properties File object
* @param encoding the encoding
*/
public static Prop use(File file, String encoding) {
Prop result = map.get(file.getName());
if (result == null) {
synchronized (PropHelper.class) {
result = map.get(file.getName());
if (result == null) {
result = new Prop(file, encoding);
map.put(file.getName(), result);
if (PropHelper.prop == null) {
PropHelper.prop = result;
}
}
}
}
return result;
}
public static Prop useless(String fileName) {
Prop previous = map.remove(fileName);
if (PropHelper.prop == previous) {
PropHelper.prop = null;
}
return previous;
}
public static void clear() {
prop = null;
map.clear();
}
public static Prop append(Prop prop) {
synchronized (PropHelper.class) {
if (PropHelper.prop != null) {
PropHelper.prop.append(prop);
} else {
PropHelper.prop = prop;
}
return PropHelper.prop;
}
}
public static Prop append(String fileName, String encoding) {
return append(new Prop(fileName, encoding));
}
public static Prop append(String fileName) {
return append(fileName, "UTF-8");
}
public static Prop appendIfExists(String fileName, String encoding) {
try {
return append(new Prop(fileName, encoding));
} catch (Exception e) {
return PropHelper.prop;
}
}
public static Prop appendIfExists(String fileName) {
return appendIfExists(fileName, "UTF-8");
}
public static Prop append(File file, String encoding) {
return append(new Prop(file, encoding));
}
public static Prop append(File file) {
return append(file, "UTF-8");
}
public static Prop appendIfExists(File file, String encoding) {
if (file.exists()) {
append(new Prop(file, encoding));
}
return PropHelper.prop;
}
public static Prop appendIfExists(File file) {
return appendIfExists(file, "UTF-8");
}
public static Prop getProp() {
if (prop == null) {
throw new IllegalStateException("Load propties file by invoking PropHelper.use(String fileName) method first.");
}
return prop;
}
public static Prop getProp(String fileName) {
return map.get(fileName);
}
public static String get(String key) {
return getProp().get(key);
}
public static String get(String key, String defaultValue) {
return getProp().get(key, defaultValue);
}
public static Integer getInt(String key) {
return getProp().getInt(key);
}
public static Integer getInt(String key, Integer defaultValue) {
return getProp().getInt(key, defaultValue);
}
public static Long getLong(String key) {
return getProp().getLong(key);
}
public static Long getLong(String key, Long defaultValue) {
return getProp().getLong(key, defaultValue);
}
public static Boolean getBoolean(String key) {
return getProp().getBoolean(key);
}
public static Boolean getBoolean(String key, Boolean defaultValue) {
return getProp().getBoolean(key, defaultValue);
}
public static boolean containsKey(String key) {
return getProp().containsKey(key);
}
}