zoukankan      html  css  js  c++  java
  • Java 读写Properties配置文件

    1.Properties类与Properties配置文件

    什么是java的配置文件?  在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

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

    2.Properties中的主要方法

    1. getProperty / setProperty

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

    2. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。

    3. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

    4. store ( OutputStream out, String comments),将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

    3. 编写读取.properties的两种方式

    //方式一:
    		File file = new File("aa.properties");
    		Properties pro = new Properties();
    		pro.setProperty("1", "张三");
    		pro.setProperty("2", "李四");
    		pro.store(new PrintStream(file), "utf-8");
    		pro.load(new FileInputStream(file));
    		
    		System.out.println(pro.getProperty("1"));
    		System.out.println(pro.getProperty("2"));
    

       

    //方式二:
    		File fi = new File("fil.properties");
    		Properties pro  = new Properties();
    		pro.put("1", "你的");
    		pro.put("2", "真的");
    		pro.store(new PrintStream(fi), "UTF-8");
    		pro.load(new FileInputStream(fi));
    		
    		System.out.println(pro.get("1"));
    		System.out.println(pro.get("2"));
    

     

  • 相关阅读:
    linux操作提示:“Can't open file for writing”或“operation not permitted”的解决办法
    CSS中background:url(图片) 不能显示的问题
    CSS3background-size背景图片尺寸属性
    在GitHub上成果预览
    快速上手GitHub上传代码
    css布局模型(1)
    css+div浮动怎么让它在窗口大小变化时不改变位置
    node.js基于express框架搭建一个简单的注册登录Web功能
    node.js 安装使用http-server
    grunt安装与运行
  • 原文地址:https://www.cnblogs.com/gshao/p/10217574.html
Copyright © 2011-2022 走看看