3. Loading and using Properties files; 3. Loading properties
1. Introduction to Properties
The Properties class is inherited from HashTable and provides similar methods as the implementation class HashMap of Map. It was available in the early stages of Java programming and has almost no changes. The Tiger version of J2SE enhances this class, not only can it be used to specify multiple key-value pairs separated by equal signs in a single row (the key-value pairs and values are separated by equal signs ), you can also load and save these key-value pairs using XML files..
Ii. Loading and simple use of Properties
1. Path Storage
2. Information Configuration
name = Lilyage = 22
3. Simple loading and use
package com.my.utils;import java.io.IOException;import java.io.InputStream;import java.util.Properties;public class LoadProp { public static void main(String[] args) { // TODO Auto-generated method stub Properties prop = new Properties(); InputStream in = LoadProp.class.getClassLoader().getResourceAsStream("config/prop.properties"); try { prop.load(in); System.out.println(prop.get("name")); prop.setProperty("name", "Lucy"); System.out.println(prop.get("name")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}
4. Use java. util. Enumeration to get all keys
package com.my.utils;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.Properties;public class LoadProp { @SuppressWarnings("unchecked") public static void main(String[] args) { // TODO Auto-generated method stub Properties prop = new Properties(); InputStream in = LoadProp.class.getClassLoader().getResourceAsStream("config/prop.properties"); Enumeration<String> en = null; String key = null; try { prop.load(in); en = (Enumeration<String>) prop.propertyNames(); while (en.hasMoreElements()) { key = (String) en.nextElement(); System.out.println(key); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}