1.读取项目根路径下的properties文件比较简单也是比较常见的一种操作。
具体代码如下:
package com.xuanen.util;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
public class PropertyUtil {
private static Properties propertie;
private static Logger logger = Logger.getLogger(PropertyUtil.class);
/**
* 读取配置文件
*/
public static Properties init()
{
if (propertie == null)
{
propertie = new Properties();
try
{
propertie = PropertiesLoaderUtils.loadProperties(new ClassPathResource("common.properties"));
}
catch (Exception ex)
{
logger.error(ex.getMessage());
}
}
return propertie;
}
/**
* 获取solr的config路径
*/
public static String getDateConfigXMLPath()
{
propertie = init();
String path = propertie.getProperty("dateConfigPath");
return path;
}
}
2.读取磁盘上任意位置的properties文件不常见,但是也要掌握。代码如下
public class GetSolrCreateDate
{
// 获取dataimport.properties索引的创建时间的配置文件
//此处可替换成磁盘任意位置的properties文件位置 例如:E:/dataimport.properties
private static String path = PropertyUtil.getDateConfigXMLPath().replace("data-config.xml", "") + "dataimport.properties";
private static Properties propertie;
private static Logger logger = Logger.getLogger(PropertyUtil.class);
/**
* 读取配置文件
*/
public static Properties init()
{
if (propertie == null)
{
propertie = new Properties();
try
{
if (FileUtils.isExcite(path)){
propertie = PropertiesLoaderUtils.loadProperties(new PathResource(path));
}
}
catch (Exception ex)
{
logger.error(ex.getMessage());
}
}
return propertie;
}
// 根据表名获取索引改变的时间
public static String getCreateDateByTableName(String tableName)
{
propertie = init();
String data = propertie.getProperty(tableName+".last_index_time");
if (StringUtils.isNotBlank(data))
{
return data;
}
return null;
}
}