項目中需要用到操作properties文件中的數據,記錄一下
package com.bonc.savepic.save; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * @Author clj * @SinceDate 2019/3/26 17:05 * @Description */ public class PropertiesUtil { /** * 獲取Properties對象 * @return */ public static Properties getProperties(){ Properties properties = new Properties(); InputStream inputStream = null; try { //data.properties在resources目錄下 inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("data.properties"); properties.load(inputStream); } catch (FileNotFoundException e) { System.out.println("data.properties文件未找到!"); } catch (IOException e) { System.out.println("出現IOException"); } finally { try { if (null != inputStream){ inputStream.close(); } } catch (IOException e) { System.out.println("data.properties文件流關閉出現異常"); } } return properties; } /** * 根據key查詢value值 * @param key key * @return */ public static String getValue(String key){ Properties properties = getProperties(); String value = properties.getProperty(key); return value; } /** * 新增/修改數據 * @param key * @param value */ public static void setValue(String key, String value){ Properties properties = getProperties(); properties.setProperty(key, value); //此處獲取的路徑是target下classes //這里的path是項目文件的絕對路徑 //先獲取項目絕對路徑:Thread.currentThread().getContextClassLoader().getResource("").getPath(); //然后在項目路徑后面拼接"properties/sysConfig.properties"; // 原注釋 String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); path = path + "data.properties"; FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(path); properties.store(fileOutputStream, "注釋"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != fileOutputStream){ fileOutputStream.close(); } } catch (IOException e) { System.out.println("data.properties文件流關閉出現異常"); } } } /** * 刪除和修改只有語句不同 * properties.remove(key); */ }