Properties也是一个键值对
内存中的数据是临时的,文件中的数据保存后永远持久存储。
Properties类中的数据存储在文件中。
- 创建属性文件
右键包 -----new ----file
- 编写属性文件
name叫key,但是在Properties文件中,通常叫key为属性
叫value为属性值,所有的属性值都是字符串类型。
例如:
Person类 name age
name = lichen
age = 10
package com.njwbhz.March.week1.part0303;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
所有properties文件的作用:配置文件。
package com.njwbhz.March.week1.part0303;
import java.util.Properties;
public class TestPerson {
public static void main(String[] args) throws Exception {
// Person person = new Person("林辰" , 23);
//读取properties文件
//借助properties对象
Properties properties = new Properties();
//properties对象和my.propreties对象做关联
properties.load(TestPerson.class.getResourceAsStream("my.propreties"));
//读取配置文件中的name和age
// String name = (String) properties.get("name");
String name = properties.getProperty("name");
// int age = properties.getProperty("age");
int age = Integer.valueOf(properties.getProperty("name"));
Person person = new Person(name,age);
System.out.println(person);
}
}