properties文件是我們經常需要操作一種文件,它使用一種鍵值對的形式來保存屬性集。
無論在學習上還是工作上經常需要讀取,修改,刪除properties文件里面的屬性。
本文通過操作一個properties去認識怎樣操作properties文件。
Java提供了Properties這個類Properties(Java.util.Properties),用於操作properties文件。
這是配置文件,file.properties
type=mysql driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/db?characterEncoding=utf-8 username=root password=root
public class PropertiesDemo { public static final Properties p = new Properties(); public static final String path = "file.properties";
初始化:
/** * 通過類裝載器 初始化Properties */ public static void init() { //轉換成流 InputStream inputStream = PropertiesDemo.class.getClassLoader().getResourceAsStream(path); try { //從輸入流中讀取屬性列表(鍵和元素對) p.load(inputStream); } catch (IOException e) { e.printStackTrace(); } }
獲取:
/** * 通過key獲取value * @param key * @return */ public static String get(String key) { return p.getProperty(key); }
修改或者新增:
/** * 修改或者新增key * @param key * @param value */ public static void update(String key, String value) { p.setProperty(key, value); FileOutputStream oFile = null; try { oFile = new FileOutputStream(path); //將Properties中的屬性列表(鍵和元素對)寫入輸出流 p.store(oFile, ""); } catch (IOException e) { e.printStackTrace(); } finally { try { oFile.close(); } catch (IOException e) { e.printStackTrace(); } } }
刪除:
/** * 通過key刪除value * @param key */ public static void delete(String key) { p.remove(key); FileOutputStream oFile = null; try { oFile = new FileOutputStream(path); p.store(oFile, ""); } catch (IOException e) { e.printStackTrace(); } finally { try { oFile.close(); } catch (IOException e) { e.printStackTrace(); } } }
獲取所有:
/** * 循環所有key value */ public static void list() { Enumeration en = p.propertyNames(); //得到配置文件的名字 while(en.hasMoreElements()) { String strKey = (String) en.nextElement(); String strValue = p.getProperty(strKey); System.out.println(strKey + "=" + strValue); } }
測試:
public static void main(String[] args) { PropertiesDemo.init(); //修改 PropertiesDemo.update("password","123456"); System.out.println(PropertiesDemo.get("password")); //刪除 PropertiesDemo.delete("username"); System.out.println(PropertiesDemo.get("username")); //獲取所有 PropertiesDemo.list(); }