关于读取properties配置文件网上有很多介绍的,这里介绍一种自动适配properties文件格式的办法。
主要的设计思路,其实就是想办法获取到当前文件的编码格式,这里用到的工具包引用如下:
(用到了工具包juniversalchardet)
<dependency>
<groupId>com.github.albfernandez</groupId>
<artifactId>juniversalchardet</artifactId>
<version>2.3.2</version>
</dependency>
该工具包能识别的的格式有
- Chinese
ISO-2022-CN
BIG-5
EUC-TW
HZ-GB-2312 - Cyrillic
ISO-8859-5
KOI8-R
WINDOWS-1251
MACCYRILLIC
IBM866
IBM855 - Greek
ISO-8859-7
WINDOWS-1253
Hebrew
…
Unicode
UTF-8
UTF-16BE / UTF-16LE
Others
下面直接上代码
Configure类,用于读取配置文件
package file.properties;
import java.io.*;
import java.util.*;
import java.util.concurrent.locks.*;
public class Configure {
private Configure() throws IOException {
init();//初始化配置文件
}
private void init() throws IOException {
loadData(PATH, properties); //加载配置文件
}
/**
* 单例模式获取当前对象
* */
public static Configure get() throws IOException {
if(configure != null) {
return configure;
}
lock.lock();
try {
if(configure == null) {
configure = new Configure();
}
return configure;
}
finally {
lock.unlock();
}
}
/**
* 加载配置文件
* */
private void loadData(String path, Properties properties) throws IOException {
InputStream resourceAsStream = Configure.class.getResourceAsStream("/" + path);//获取文件流
InputStreamReader in = null;
try {
in = new InputStreamReader(resourceAsStream, ConfiguerUtil.getCoding(path));//getCoding()获取文件格式
if(in != null) {
properties.load(in);//加载到properties对象
}
else {
throw new IOException("文件流传输失败!");
}
}
finally {
if(in != null) {
in.close();
}
resourceAsStream.close();
}
}
/**
* 读取配置
* */
public String get(String key) {
Object value = properties.get(key);
return value == null ? null : String.valueOf(value);
}
private static Lock lock = new ReentrantLock();
private final String PATH = "config.properties";//配置文件路径
Properties properties = new Properties();
private static Configure configure;//单例模式获取对象
}
ConfiguerUtil,配置文件工具类
package file.properties;
import java.io.*;
import org.mozilla.universalchardet.UniversalDetector;
public class ConfiguerUtil {
/**
* 获取文件格式
* */
public static String getCoding(String path) throws IOException {
InputStream fileInputStream = ConfiguerUtil.class.getResourceAsStream("/" + path);
return getCoding(fileInputStream);
}
/**
* 获取文件格式
* */
public static String getCoding(InputStream fis) throws IOException {
try {
byte[] buf = new byte[1024];
UniversalDetector detector = new UniversalDetector();
int nread;
while((nread = fis.read(buf)) > 0 && !detector.isDone()) {
detector.handleData(buf, 0, nread);
}
detector.dataEnd();
String encoding = detector.getDetectedCharset();
detector.reset();
return encoding == null ? "utf-8" : encoding;//默认采用utf-8
}
finally {
fis.close();
}
}
}
经过测试,当properties用text记事本另存为其他格式时,依然可以正常读取。