Use java. util. Properties to quickly import the configuration file,
1. java. util. Properties class inheritance relationship
The Properties class indicates a set of persistent Properties. Attributes can be saved to a stream or loaded from a stream. Each key in the attribute list and its corresponding value is a string.
Inheritance relationship:
java.lang.Object java.util.Dictionary<K,V> java.util.Hashtable<Object,Object> java.util.Properties
public class Properties extends Hashtable<Object,Object>
Important methods (loading attributes from a stream ):
public void load(InputStream inStream) throws IOExceptionpublic void load(Reader reader)throws IOExceptionpublic void loadFromXML(InputStream in) throws IOException,InvalidPropertiesFormatException
The load method can read various types of string streams, including XML. Here we only introduce the simple text structure. The following formats are valid:
Truth = BeautyTruth =Truth:BeautyTruth :Beauty
2. Create configuration text
The configuration file is in the format of key = value. It can be empty rows or empty values (the value is null when the data is obtained ). # Is a comment and can be ignored.
Example: dataSource. properties
# Database connection string URL = jdbc: oracle: thin: @ 127.0.0.1: 1521: myOrcluserName = oraclepassWord = oracle
3. Use a java program to read information
Because the Map data returned by the load method in the java. util. Properties class is called as Map data as long as the configuration file is loaded.
Example: MyTest. java
import java.io.FileInputStream;import java.io.IOException;import java.util.Properties;Class MyTest{ public static void initDS() { FileInputStream inStream = null; try { inStream = new FileInputStream("dataSource.properties"); Properties prop = new Properties(); prop.load(inStream); String URL = prop.getProperty("URL"); String userName = prop.getProperty("userName"); String passWord = prop.getProperty("passWord"); System.out.println(URL); System.out.println(userName); System.out.println(passWord); } catch (IOException ex) { ex.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { } } } }}