zoukankan      html  css  js  c++  java
  • Properties

    Properties配置文件说明

    • Properties类对应.properties文件。文件内容是键值对,键值对之间使用"="或空格隔开。开头是"#"的表示注释
    • Properties类在加载.properties文件时使用的iso8859-1的编码。所以这个文件中的中文要特殊处理:如果这个配置文件中有中文就必须要进行转义,使用native2ascii.exe命令操作:
     native2ascii d:/my.properties d:/my2.properties

        使用Properties类中的load(InputStream) 方法可以加载配置文件,使用其中的store(OutputStream) 方法可以保存配置到指定文件。

        更多的信息可以看Properties类的API文档。

    加载配置文件

    public static void testLoadProperties() throws Exception {
        Properties properties = new Properties();
    
        InputStream in = new FileInputStream("E:/loaderman/config.properties");
        properties.load(in); // 加载
        in.close();
    
        System.out.println(properties);
    }

    写配置文件

    public static void testStoreProperties() throws Exception {
        // 准备配置信息
        Properties properties = new Properties();
        properties.setProperty("name", "李四");
        properties.setProperty("age", "20");
    
        // 准备
        OutputStream out = new FileOutputStream("d:/my.properties");
        String comments = "这是我的配置文件";
    
        // 写出去
        properties.store(out, comments);
        out.close();
    }

    示例代码:

    public class DBUtil {
        
        static Properties properties = new Properties();
        
        static{
            try {
                Class clazz = DBUtil.class;
                InputStreamReader fileReader =
                new InputStreamReader(clazz.getResourceAsStream("/db.properties"));
                properties.load(fileReader);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public static String getUserName(){
            String userName =properties.getProperty("userName");
            return userName;
        }
        
        public static String getPassword(){
            return    properties.getProperty("password");
        }
        public static void main(String[] args) {
            System.out.println("用户名:"+ getUserName());
            System.out.println("密码: "+  getPassword());
        }
    }

    特点:

    1. 键和值都是字符串

    2. 可以和IO流进行配合使用


    父类是 Hashtable


    特有的功能:

    public Object setProperty(String key , String value) ;

    public String getProperty(String key) ;

    public Set<String> stringPropertyNames() ;

    public void load(Reader r)

    public void load(InputStream in)

    public void store(Writer w)

    public void store(OutputStream out)

     

     

  • 相关阅读:
    单点登录实现机制:web-sso
    阿里云API网关(16)客户端请求的https支持
    阿里云API网关(15)监控预警
    BZOJ1802: [Ahoi2009]checker(性质分析 dp)
    LOJ#505. 「LibreOJ β Round」ZQC 的游戏(最大流)
    LOJ#6085. 「美团 CodeM 资格赛」优惠券(set)
    洛谷P3924 康娜的线段树(期望 前缀和)
    BZOJ2337: [HNOI2011]XOR和路径(期望 高斯消元)
    2016计蒜之道复赛 百度地图的实时路况(Floyd 分治)
    洛谷P2881 [USACO07MAR]排名的牛Ranking the Cows(bitset Floyd)
  • 原文地址:https://www.cnblogs.com/loaderman/p/6407746.html
Copyright © 2011-2022 走看看