在程序中我们可能会遇到想要修改属性的某些初始化值时,一般的做法是修改代码里面的初始值,使用properties可以让我们不修改代码就可以实现修改初始值的功能.
properties的使用方法和HashMap的存储是一样的,都是通过key-value的方法,不同的是,会生成一个.properties的文件保存数据.
public static void main(String[] args) {
// Property 属性 继承自Hashtable
// Hashtable 和Hashmap是一样的
// 区别在于Hashtable中key和value的值都不能为null,Hashmap可以
Hashtable<String, String> ht = new Hashtable<String,String>();
// ht.put(null, null); NullPointerException
HashMap<String, String> ht1 = new HashMap<String,String>();
}
创建一个properties文件
public class Test2 {
public static void main(String[] args) {
// 属性列表
Properties properties = new Properties();
properties.setProperty("name", "张三");
properties.setProperty("age", "18");
// 通过输出流保存到硬盘上
// 相对路径,保存在工程目录下
try (FileOutputStream fileOutputStream = new FileOutputStream("people.properties");){
properties.store(fileOutputStream, "Save info");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
从文件中读取
import java.io.FileInputStream;
import java.util.Properties;
public class Test3 {
public static void main(String[] args) {
// 通过key-value 的访问方式
// 可以不通过修改程序获取不同的执行效果
// 使用properties从配置文件中加载属性的值,可以随着文件的变化而变化
Properties properties = new Properties();
try (FileInputStream fileInputStream = new FileInputStream("people.properties");){
// 从指定的流中加载数据
properties.load(fileInputStream);
} catch (Exception e) {
}
// 加载完毕,获取数据 根据key获取value
String name = properties.getProperty("name");
String age = properties.getProperty("age");
String school = properties.getProperty("school");
System.out.println(name + age + school);
}
}