java 配置信息类 Properties 的简单使用

Properties :(配置信息类) 是一个表示持久性的集合 ,继承 Hashtable ,存值是以键-值得方式
   主要用于生产配置文件和读取配置文件信息。

简单的实例:

 1 import java.io.FileNotFoundException;
 2 import java.io.FileReader;
 3 import java.io.FileWriter;
 4 import java.io.IOException;
 5 import java.util.Map.Entry;
 6 import java.util.Properties;
 7 import java.util.Set;
 8 
 9 public class properties {
10 
11     public static void main(String[] args) throws IOException {
12         createPropert();
13         readPropert();
14     }
15     
16     //(一)创建配置信息类
17     public static void  createPropert() throws IOException {
18         //1.创建对象
19         Properties pt = new Properties();
20         
21         //2.配置对象信息(键值都是字符串类型)
22         pt.setProperty("初一", "1101");
23         pt.setProperty("小二", "1102");
24         pt.setProperty("张3", "1103");
25         pt.setProperty("lisi", "1104");
26         
27         //3.将配置好的对象文件存入磁盘(两个方法都可以)
28         //(1)store(new FileWriter("C:\\.."))        如果需要写入中文时建议使用字符流
29         //(2)store(new FileOutputStream(C:\\..))    字节流
30         pt.store(new FileWriter("C:\\Users\\bg\\Desktop\\配置流.properties"), "这是对文件的描述信息:");
31     }
32     
33     
34     //(二)读取配置对象的信息
35     public static void  readPropert() throws FileNotFoundException, IOException {
36         //1.创建对象
37         Properties pt = new Properties();
38         
39         //2.根据路径 读取配置对象数据 load(new FileReader("C:\\.."))
40         pt.load(new FileReader("C:\\Users\\bg\\Desktop\\配置流.properties"));
41         
42         //3.遍历集合(配置对象数据)  
43         //集合是可以通过foreach循环来遍历的
44         Set<Entry<Object, Object>> entrys = pt.entrySet();
45         for (Entry<Object, Object> entry : entrys) {
46             System.out.println("name:"+entry.getKey() +"    id:"+ entry.getValue());
47         }
48     }
49 }

打印结果:

name:初一    id:1101
name:lisi    id:1104
name:小二    id:1102
name:张3    id:1103

相关方法:

构造方法:Properties();//无默认值

     Properties(Properties defaults);  //指定默认值

配置信息:setProperties(key,value);  //键值都是字符串类型

写入数据:(1)store(new FileWriter("C:\\.."),"配置信息的描述语") ;  //如果需要写入中文时建议使用字符流

     (2)store(new FileOutputStream(C:\\..),"配置信息的描述语");  // 字节流

读取数据: load(new FileReader("C:\\.."));  //字符流读取

转载于:https://www.cnblogs.com/bigerf/p/6143576.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值