Items are often used in json,xml,properties, text files, etc., as configuration files. Used to store connection strings or other configuration parameters.
This document records the properties.
Properties file, which stores the format key = value. For example, create a new Config.properties file:
12345678 |
####这里是config.properties文件,存储数据库信息#### #数据库ip connip=192.168.10.29 username= user1 password=pwd1 #username= user2 #password=test2 user= "user1" |
Properties File Features:
1, key-value pair format
2,= after the equals sign, the spaces in front of the value are automatically ignored
3, the space following the value is not ignored
4,= the double quotation mark after the equal sign, does not ignore
5, #井号后面内容, for comment, ignore
so , read config.properties, get the value by key, get the result:
Connip for [192.168.10.29]
Username for [User1]
password for [pwd1??]? Note here that there are spaces behind the pwd1.
User for ["user1"] here to note, values, including double quotes.
The class for manipulating Properties in Java is, java.util.Properties.
The method of reading properties is relatively simple
Three steps:
1, load the resource; 2, get the value by key; 3, test output
1234567891011 |
public static void main(String[] args) throws IOException {
Properties properties =
new Properties();
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(
"config.properties"
);
properties.load(inputStream);
String result1 = properties.getProperty(
"connip"
);
String result2 = properties.getProperty(
"sdfds"
,
"error"
);
System.err.println(result1);
System.err.println(result2);
}
|
The output is:
192.168.10.29
Error
Program Description:
1. Resource Loading
Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream ("config.properties");
This uses the format of the resource loading method.
2, properties note GetProperty, there is an overload.
One is to get the value directly
The other is to return the default value when key does not exist
Finish
About resource loading:
1234567891011 |
public class PropertiesTest {
public static void main(String[] args) throws IOException {
String path1 = Thread.currentThread().getContextClassLoader().getResource(
"."
).getPath();
String path2 = PropertiesTest.
class
.getClassLoader().getResource(
"."
).getPath();
String path3 = PropertiesTest.
class
.getResource(
"."
).getPath();
System.err.println(
"path1:" + path1);
System.err.println(
"path2:" + path2);
System.err.println(
"path3:" + path3);
}
}
|
Output:
path1:/g:/alljavaprojece/myeclipse10project/mydemo2/bin/
path2:/g:/alljavaprojece/myeclipse10project/mydemo2/bin/
path3:/g:/alljavaprojece/myeclipse10project/mydemo2/bin/my/properties/
Garbled
Help classes to read properties:
Go from blog: http://www.weixuehao.com/archives/357
Java Read Properties configuration file