Properties类
在Properties类中,以键值对的方式来存储信息 key=value ,并且key值不能重复。他继承了HashTable类,以Map的形式来进行存放。
读取
当我们使用数据库时,常常会使用到root,password等信息,这时我们就可以通过创建Properties类来实现这些信息的快速读取。
package IO流;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class TheProperties {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Java 基础\\IO流\\Database.properties"));
String line;
while ((line = br.readLine())!=null){
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
System.out.println("io exception");
}
}
}
//properties类-->Database.properties
driver=com.mysql
url=jdbc:mysql
username=root
password=123456
这样即可获取到properties类中的资源
当然我们也可以通过**public void load(InputStream inStream)**来进行数据的输入读取
在输出时,我们也可以分别输出key与value的值,或者是对其进行筛选。
while ((line = br.readLine())!=null){
String[] spilt = line.split("=");
if ("ip".equals(spilt[0])){
System.out.println("This is ip.Value is "+spilt[1]);
}
}
修改
我们也可以对其properties类中的数据进行修改。我们常常使用 Properties类中所提供的
**setProperty(key value)**来进行对数据的修改与添加。如果在资源中已经有了当前设置的key值,则会修改value值。而如果不存在当前的key值,则会新建一个新的key-value值对。
最后在对其进行储存。
String filePath = "D:\\aa.properties";
Properties properties = new Properties();
properties.setProperty("ip","114514");
properties.setProperty("new","It is New");
try {
//comments为注解,一般为空
properties.store(new FileOutputStream(filePath),null);
} catch (Exception e) {
e.printStackTrace();
}