今天我们来总结Properties
package com.NicMark.Properties01;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Proper01 {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\Mysql.properties"));
String line = "";
while((line = bufferedReader.readLine())!=null){
String[] split = line.split("=");
if("ip".equals(split[0])){
System.out.println(split[0]+"值是:"+split[1]);}
}
bufferedReader.close();
}
}
这是Mysql.properties的内容
ip=192.168.100.100
user=root
pwd=12345
如果说我们需要取其中单独的一个key的值,我们需要split it,这显然非常麻烦,因此,这也是properties的用处
package com.NicMark.Properties01;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class Properties02 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(new FileReader("src\\Mysql.properties"));
properties.list(System.out);
System.out.println("====================");
String user = properties.getProperty("user");
System.out.println(user);
}
}
如若想去的某个key的值,我们只需要properties.getProperty() 括号里所填是数据库中的key。
创建Properties
package com.NicMark.Properties01;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Properties03 {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.setProperty("charset","utf8");
properties.setProperty("user","汤姆");
properties.setProperty("pwd","abc111");
properties.store(new FileOutputStream("src\\mysql2.properties"),null);
}
}
在创建时,我们需要先new一个properties对象Properties properties = new Properties(); 再用setProperty(),逗号前是key,逗号后是内容
Properties properties = new Properties();
properties.setProperty("charset","utf8");
properties.setProperty("user","汤姆");
properties.setProperty("pwd","abc111");
然后,再用store(),将数据库存储到指定地点
properties.store(new FileOutputStream("src\\mysql2.properties"),null)
后边的null,是数据库的小标签,通常用#开头
===================================
OK那么这次总结也结束了,期待有缘再见
|