有時候我們希望處理properties文件,properties文件是鍵值對的文件形式,我們可以借助Properties類操作。
工具類如下:(代碼中日志采用了slf4j日志)
package cn.xm.exam.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map.Entry; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 操作properties文件的工具類(此工具類的file都是src目錄下的properties文件,編譯之后在build目錄下) * * @author QiaoLiQiang * @time 2018年11月3日下午12:05:32 */ public class PropertiesFileUtils { private static final Logger log = LoggerFactory.getLogger(PropertiesFileUtils.class); /** * 構造函數私有化 */ private PropertiesFileUtils() { } /** * 保存或更新properties文件中的key * * @param fileName * @param key * @param value */ public static void saveOrUpdateProperty(String fileName, String key, String value) { Properties properties = new Properties(); InputStream inputStream; OutputStream outputStream; try { String path = ResourcesUtil.class.getClassLoader().getResource(fileName).getPath(); log.debug("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); properties.setProperty(key, value); // 保存到文件中(如果有的話會自動更新,沒有會創建) outputStream = new FileOutputStream(new File(path)); properties.store(outputStream, ""); outputStream.close(); inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } } /** * 獲取Properties * * @param fileName * @param key * @return */ public static String getPropertyValue(String fileName, String key) { Properties properties = new Properties(); InputStream inputStream; String value = ""; try { String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath(); log.info("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); value = properties.getProperty(key); // 保存到文件中(如果有的話會自動更新,沒有會創建) inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } return value; } /** * 獲取Properties * * @param fileName * @return */ public static Properties getProperties(String fileName) { Properties properties = new Properties(); InputStream inputStream; try { String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath(); log.info("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } return properties; } /** * 獲取Properties * * @param fileName * @return */ public static Properties removeProperty(String fileName, String key) { Properties properties = new Properties(); InputStream inputStream; OutputStream outputStream; try { String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath(); log.info("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); log.info("properties -> {}", properties); if (properties != null && properties.containsKey(key)) { log.info("remove key:{}", key); properties.remove(key); } // 保存到文件中(將properties保存到文件) outputStream = new FileOutputStream(new File(path)); properties.store(outputStream, ""); outputStream.close(); inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } return properties; } public static void main(String[] args) { // 保存三個 最后一個相當於更新 PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "a", "aaa"); PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "b", "bbb"); PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "c", "ccc"); PropertiesFileUtils.saveOrUpdateProperty("settings.properties", "a", "AAA"); // 獲取所有的properties Properties properties = PropertiesFileUtils.getProperties("settings.properties"); System.out.println(properties); // 刪除a PropertiesFileUtils.removeProperty("settings.properties", "a"); // 獲取所有的properties Properties properties1 = PropertiesFileUtils.getProperties("settings.properties"); System.out.println(properties1); } }
結果:
{b=bbb, a=AAA, c=ccc}
{b=bbb, c=ccc}
解釋:
Properties是繼承了HashTable的一個普通類,所以我們可以簡單的認為操作Properties就是在操作HashTable。
public class Properties extends Hashtable<Object,Object> { private static final long serialVersionUID = 4112578634029874840L; protected Properties defaults; 。。。 }
由於HasTable鍵不可以重復,所以我們在saveOrUpdateProperty中直接setProperty的時候如果沒有key會創建key,如果key存在會覆蓋原來的值。
properties.load(inputStream);是將properties文件中的key=value的數據加載到properties中;
properties.store(outputStream, "");是將properties保存到一個文件中。
補充:上面代碼還可以進一步將properties文件的位置封裝全路徑:
package cn.xm.exam.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author QiaoLiQiang * @time 2018年11月3日下午12:05:32 */ public class PropertiesFileUtils { private static final Logger log = LoggerFactory.getLogger(PropertiesFileUtils.class); /** * 構造函數私有化 */ private PropertiesFileUtils() { } /** * 保存或更新properties文件中的key * * @param fileName * @param key * @param value */ public static void saveOrUpdateProperty(String fileName, String key, String value) { Properties properties = new Properties(); InputStream inputStream; OutputStream outputStream; try { String path = ResourcesUtil.class.getClassLoader().getResource(fileName).getPath(); log.debug("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); properties.setProperty(key, value); // 保存到文件中(如果有的話會自動更新,沒有會創建) outputStream = new FileOutputStream(new File(path)); properties.store(outputStream, ""); outputStream.close(); inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } } /** * 獲取Properties * * @param fileName * @param key * @return */ public static String getPropertyValue(String fileName, String key) { Properties properties = new Properties(); InputStream inputStream; String value = ""; try { String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath(); log.info("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); value = properties.getProperty(key); // 保存到文件中(如果有的話會自動更新,沒有會創建) inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } return value; } /** * 獲取Properties * * @param fileName * @return */ public static Properties getProperties(String fileName) { Properties properties = new Properties(); InputStream inputStream; try { String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath(); log.info("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } return properties; } /** * 獲取Properties * * @param fileName * @return */ public static Properties removeProperty(String fileName, String key) { Properties properties = new Properties(); InputStream inputStream; OutputStream outputStream; try { String path = PropertiesFileUtils.class.getClassLoader().getResource(fileName).getPath(); log.info("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); log.info("properties -> {}", properties); if (properties != null && properties.containsKey(key)) { log.info("remove key:{}", key); properties.remove(key); } // 保存到文件中(將properties保存到文件) outputStream = new FileOutputStream(new File(path)); properties.store(outputStream, ""); outputStream.close(); inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } return properties; } /** * 保存或更新properties文件中的key * * @param path * 文件全路徑 * @param key * @param value */ public static void saveOrUpdatePropertyByFilePath(String path, String key, String value) { Properties properties = new Properties(); InputStream inputStream; OutputStream outputStream; try { log.debug("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); properties.setProperty(key, value); // 保存到文件中(如果有的話會自動更新,沒有會創建) outputStream = new FileOutputStream(new File(path)); properties.store(outputStream, ""); outputStream.close(); inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } } /** * 獲取Properties * * @param path * 文件全路徑 * @param key * @return */ public static String getPropertyValueByFilePath(String path, String key) { Properties properties = new Properties(); InputStream inputStream; String value = ""; try { log.info("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); value = properties.getProperty(key); // 保存到文件中(如果有的話會自動更新,沒有會創建) inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } return value; } /** * 獲取Properties * * @param path * 文件全路徑 * @return */ public static Properties getPropertiesByFilePath(String path) { Properties properties = new Properties(); InputStream inputStream; try { log.info("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } return properties; } /** * 獲取Properties * * @param path * 文件全路徑 * @param key * key值 * @return */ public static Properties removePropertyByFilePath(String path, String key) { Properties properties = new Properties(); InputStream inputStream; OutputStream outputStream; try { log.info("path -> {}", path); inputStream = new FileInputStream(new File(path)); properties.load(inputStream); log.info("properties -> {}", properties); if (properties != null && properties.containsKey(key)) { log.info("remove key:{}", key); properties.remove(key); } // 保存到文件中(將properties保存到文件) outputStream = new FileOutputStream(new File(path)); properties.store(outputStream, ""); outputStream.close(); inputStream.close(); } catch (FileNotFoundException e) { log.error("saveOrUpdateProperty error", e); } catch (IOException e) { log.error("saveOrUpdateProperty error", e); } return properties; } }
補充:如果是spring項目讀取jar包中的配置可以用 ClassPathResource 進行讀取:
/** * 獲取文件中對應的key的名稱 * * @param fileName * @param key * @return */ public static String getPropertyValue(String fileName, String key) { Properties properties = new Properties(); InputStream inputStream = null; String value = ""; try { ClassPathResource resource = new ClassPathResource(fileName); inputStream = resource.getInputStream(); properties.load(inputStream); value = properties.getProperty(key); } catch (Exception e) { log.error("saveOrUpdateProperty error", e); } finally { IOUtils.closeQuietly(inputStream); } return value; }
補充:由於springboot打成jar包之后里面的文件不能實時修改,所以在當前程序的主目錄下創建一settings.properties文件進行操作
package cn.qs.utils.system; import java.io.File; import java.io.IOException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import cn.qs.bean.user.User; import cn.qs.utils.UUIDUtils; import cn.qs.utils.file.PropertiesFileUtils; public class MySystemUtils { private static final Logger LOGGER = LoggerFactory.getLogger(MySystemUtils.class); static { checkSettingPropertyFiles(); } private MySystemUtils() { } /** * 檢查settings.properties文件是否存在,不存在就創建 */ public static void checkSettingPropertyFiles() { File userDir = SystemUtils.getUserDir(); File propertiesFile = new File(userDir, "settings.properties"); if (!propertiesFile.exists()) { try { propertiesFile.createNewFile(); LOGGER.info("create settings.properties success, path: {}", propertiesFile.getAbsolutePath()); } catch (IOException e) { LOGGER.error("create settings.properties failed", e); } } } public static final String settings_file_path = SystemUtils.getUserDir().getAbsolutePath() + "/settings.properties"; public static String getProductName() { return getProperty("productName", "管理網"); } public static String getProperty(String key) { return getProperty(key, ""); } public static String getProperty(String key, String defaultValue) { return StringUtils.defaultIfBlank(PropertiesFileUtils.getPropertyValueByFilePath(settings_file_path, key), defaultValue); } public static void setProperty(String key, Object value) { PropertiesFileUtils.saveOrUpdatePropertyByFilePath(settings_file_path, key, String.valueOf(value)); } }
SystemUtils.getUserDir()方法獲取的是項目所在的路徑,如果是springboot打的jar包是jar包所在的目錄。