集合Properties

Properties: 是集合中唯一一个持久化的集合

概述:

Properties(Java.util.Properties),该类主要用于读取Java的配置文件,不同的编程语言有自己所支持的配置文件,配置文件中很多变量是经常改变的,为了方便用户的配置,能让用户够脱离程序本身去修改相关的变量设置。就像在Java中,其配置文件常为.properties文件,是以键值对的形式进行参数配置的。

常用方法:

1. 写入指定文件

 1 public static void main(String[] args) {
 2         Properties pr=new Properties();
 3         pr.put("name", "张三");
 4         pr.put("age", "18");
 5         
 6         try {
 7             FileWriter fw=new FileWriter(new File("src/text.properties"));
 8             pr.store(fw,"这是一段注释");
 9             
10         } catch (IOException e) {
11             e.printStackTrace();
12         }
13     }

2.从指定文件读取(最常用的读取配置文件)

public static void main(String[] args) {
        //从指定文件读取
        try {
            Properties pr=new Properties();
            FileInputStream fis= new FileInputStream(new File("src/text.properties"));
            //使用"utf-8"编码
            InputStreamReader isr=new InputStreamReader(fis,"utf-8");
            pr.load(isr);
            String name=pr.getProperty("name");
            String age=pr.getProperty("age");
            System.out.println(name+"---"+age);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }     
    }
text.properties文件
1 #\u8FD9\u662F\u4E00\u6BB5\u6CE8\u91CA
2 #Mon Oct 28 09:59:35 CST 2019
3 age=18
4 name=张三

猜你喜欢

转载自www.cnblogs.com/sunzhiqiang/p/11782616.html