工具类,关于手工读取 properties文件参数
import java.io.*;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
/**
*
*
* @Package: [cn.com.wind.Infrastructure.Core.Utils]
* @ClassName: [PropertiesUtil]
* @Description:
* [通用属性文件操作]
* @Author: [pli.kelelipeng]
* @Date: [2020年1月8日,上午9:49:21]
* @Version [V1.0]
*
*/
public class PropertiesUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private static Properties props;
static{
loadProps();
}
synchronized static private void loadProps(){
SequenceInputStream si = null;
props = new Properties();
try {
//SequenceInputStream合并多个InputStream 注意第一个文件的最后一行如果没有换行符或者注释会和下一个文件第一个并列一行
Vector<InputStream> v = new Vector<>(3);
v.addElement(PropertiesUtil.class.getResourceAsStream("/url-param.properties"));
v.addElement(PropertiesUtil.class.getResourceAsStream("/jdbc.properties"));
v.addElement(PropertiesUtil.class.getResourceAsStream("/windAuth.properties"));
Enumeration<? extends InputStream> e = v.elements();
si = new SequenceInputStream(e);
props.load(si);
} catch (FileNotFoundException e) {
logger.error("jdbc.properties文件未找到");
} catch (IOException e) {
logger.error("出现IOException");
} finally {
try {
if(null != si) {
si.close();
}
} catch (IOException e) {
logger.error("jdbc.properties文件流关闭出现异常");
}
}
}
public static String getProperty(String key){
if(null == props) {
loadProps();
}
return props.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
if(null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
/**
* 返回资源文件的 Properties 对象.
*
* @param strFile
* 传入属性文件名称串.
* @return Properties 对象
* @throws IOException
*/
public static Properties getProperties(String strFile) {
// 类装载器,仅读取类路径下文件
InputStream inStream = ClassLoader.getSystemResourceAsStream(strFile);
Properties properties = new Properties();
try {
properties.load(inStream);
return properties;
} catch (IOException e) {
String errorInfo=LoggerHelper.getStackErrorInfos(e);
LoggerHelper.LogError.error(errorInfo);
}
return null;
}
public static String getResourcePath2() {
try
{
return ResourceUtils.getURL("classpath:").getPath();
}
catch(Exception ex)
{
return null;
}
}
//在 resource目录下必须要存在的一个文件名
private static final String resouceFile="application.properties";
private static final String resouceFile2="application.yml";
/**
*
* @Title: getResourcePath
* @Description:
* 资源文件路径
* @param: @return
* @return: String
* @throws
*/
public static String getResourcePath() {
String classPath=null;
try {
File file=null;
try
{
//.properties
file= new ClassPathResource(resouceFile).getFile();
}
catch(Exception e)
{
}
if(file==null)
{
//.yml
file= new ClassPathResource(resouceFile2).getFile();
}
classPath = file.getParent();
} catch (IOException e) {
e.printStackTrace();
}
return classPath;
}
}