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; } }