Java读写Properties配置文件

朱雀 2022-08-21 06:39 348阅读 0赞

Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。

Properties中的主要方法

(1)load(InputStream inStream)

  这个方法可以从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象。

(2)store(OutputStream out, String comments)

  这个方法将Properties类对象的属性列表保存到输出流中。

(3)getProperty/setProperty

  这两个方法是分别是获取和设置属性信息。

  1. <span style="color:#000099;">import java.io.BufferedInputStream;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.InputStream;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.Map;
  8. import java.util.Properties;
  9. public class PropertyTest {
  10. public static void main(String[] args) {
  11. Properties prop = new Properties();
  12. Map<String,String> map=new HashMap<String,String>();
  13. try{
  14. //读取属性文件a.properties
  15. InputStream in = new BufferedInputStream (new FileInputStream("src/jdbc.properties"));
  16. prop.load(in); ///加载属性列表
  17. Iterator<String> it=prop.stringPropertyNames().iterator();
  18. while(it.hasNext()){
  19. String key=it.next();
  20. map.put(key, prop.getProperty(key));
  21. System.out.println(key+":"+prop.getProperty(key));
  22. }
  23. in.close();
  24. ///保存属性到b.properties文件
  25. FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加打开
  26. prop.setProperty("phone", "10086");
  27. prop.store(oFile, "The New properties file");
  28. oFile.close();
  29. }
  30. catch(Exception e){
  31. System.out.println(e);
  32. }
  33. }
  34. }</span>

发表评论

表情:
评论列表 (有 0 条评论,348人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JavaProperties配置文件

    Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。