星空网 > 软件开发 > Java

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\\bigerf\\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\\bigerf\\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:1101name:lisi  id:1104name:小二  id:1102name:张3  id:1103

相关方法:

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

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

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

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

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

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




原标题:java 配置信息类 Properties 的简单使用

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流