目录
- 1.Properties类的概述
- 2.Properties类方法
- 3.Properties类的实例
本文章的部分笔记整理来自https://www.runoob.com/java/java-properties-class.html
1.Properties类的概述Properties 类继承于 Hashtable,它表示一个持久的属性集,它的键和值都是 String 类型的。其继承关系如下图所示:
除了从 Hashtable 中所定义的方法,Properties 还定义了以下方法:
方法 作用 String getProperty(String key) 用指定的键在此属性列表中搜索属性 String getProperty(String key, String defaultProperty) 用指定的键在属性列表中搜索属性 void list(PrintStream streamOut) 将属性列表输出到指定的输出流 void list(PrintWriter streamOut) 将属性列表输出到指定的输出流 void load(InputStream streamIn) throws IOException 从输入流中读取属性列表(键和元素对) Enumeration propertyNames( ) 按简单的面向行的格式从输入字符流中读取属性列表(键和元素对) Object setProperty(String key, String value) 调用 Hashtable 的方法 put void store(OutputStream streamOut, String description) 将此 Properties 表中的属性列表(键和元素对)写入输出流 3.Properties类的实例(1)要求:Properties 集合入门使用、Properties 读取流中的数据、Properties 往流中写数据 (2)具体实现的代码如下:
# 修改之前的 student.properties address=上海 phone=13112345678 age=18 name=xiaoli
package jf_Properties; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; //案例: 演示Properties集合类的使用 public class PropertiesDemo{ public static void main(String[] args) throws Exception { //需求1: Properties 集合入门使用 method01(); //需求2: Properties 读取流中的数据 method02(); //需求3: Properties 往流中写数据 method03(); } public static void method01() { System.out.println("method01:"); //1.创建 Properties 集合. Properties pp = new Properties(); //2.添加几个元素. pp.setProperty("name", "xiaoli"); pp.setProperty("address", "beijing"); //3.打印 properties 集合. System.out.println(pp); //4.根据键获取值 System.out.println(pp.get("name")); } public static void method02() throws IOException { System.out.println("method02:"); //1.创建 Properties 集合. Properties pp = new Properties(); //2.直接从流中加载元素,加载文件的后缀名必须为.properties pp.load(new FileInputStream("E:\\testData\\student.properties")); //3.打印 properties 集合. System.out.println(pp); } private static void method03() throws IOException { System.out.println("method03:"); //1.创建 Properties 集合. Properties pp = new Properties(); //2.直接从流中加载元素 pp.load(new FileInputStream("E:\\testData\\student.properties")); System.out.println("修改之前:" + pp); //3.修改数据. pp.setProperty("address", "beijing"); pp.setProperty("name", "xiaoliu"); /* 不要写中文, 因为 properties 文件中会自动将中文转成其对应的Unicode码表形式. 在 IDEA 中看到的中文, 只是 IDEA 翻译后的, 并不是说源文件中也是中文. */ //pp.setProperty("name", "小刘"); //4.把数据从新写会流中. //pp.store(new FileOutputStream("E:\\testData\\student.properties"), "xiaoliu version2.0"); pp.store(new FileOutputStream("E:\\testData\\student.properties"), null); //5.打印properties集合. System.out.println("修改之前:" + pp); } }
(3)上述程序中的三个方法的结果分别如下: