IO+Properties联合使用
IO: 文件的读和写
Properties : 是一个Map集合,key和value都是String类型
-
Io+Properties联合使用
非常好的一个设计理念:
以后经常改变的数据,可以单独写到一个文件中,使用程序动态读取
将来只需要修改这个文件的内容,Java代码不需要改动,不需要重新编译,服务器也不需要重启,就可以动态读取信息
代码示例:
public class IoPropertiesTest01 {
public static void main(String[] args) {
/*
Properties : 是一个Map集合,key和value都是String类型
都将IO流文件中的数据加载到properties对象中
*/
FileInputStream in = null ;
try {
//新建一个输入流
in = new FileInputStream("E:\\Typora笔记\\JavaSE\\IO流\\user.txt");
//新建一个Map集合
Properties properties = new Properties();
//调用Properties对象的load方法将文件中的数据加载到Map集合
properties.load(in);//文件中的数据顺着管道加载到Map集合中,其中等号= 左边做key ,右边作为value
//通过key获取value
String username = properties.getProperty("username");
System.out.println(username);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in!=null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行结果:
admin
-
类似以上机制的这种文件被称为配置文件
-
并且当配置文件的内容格式是:
key1 = value
key2 = value
的时候,我们把这种配置文件叫做属性配置文件
-
java规范中有要求:属性配置文件建议以 .properties 结尾,但不是必须的
-
这种以 .properties结尾的文件在Java中被称为属性配置文件
-
其中 properties 对象是专门存放属性配置文件内容的一个类
-
属性配置文件中 # 是注释
-
属性配置文件的key重复的话,value会自动覆盖![最好不要有空格]