zoukankan      html  css  js  c++  java
  • Java学习笔记41(Properties类)

    Properties可以做到集合的数据持久存储

    它是map接口的一个实现类,可以使用map类的方法,

    不过存在区别:它没有泛型,规定键类型为字符串

    这个集合在以后的开发中会经常用到,比如连接数据库等

    这里简单介绍下基本用法,详细用法在后面介绍

    存储获取键值对:

    package demo;
    
    import java.util.Properties;
    import java.util.Set;
    
    public class PropertiesDemo {
        public static void main(String[] args) {
            function();
        }
        
        public static void function(){
            Properties pro1 = new Properties();
            pro1.setProperty("a", "1");
            pro1.setProperty("b", "2");
            pro1.setProperty("c", "3");
            System.out.println(pro1);
            
            String value = pro1.getProperty("c");
            System.out.println(value);
            
            Set<String> set = pro1.stringPropertyNames();
            for(String key:set){
                System.out.println(key+"="+pro1.getProperty(key));
            }
            
        }
    }

    集合特有方法:

    load方法:

    把文件中的键值对加载到集合中

    新建一个文本文件,后缀修改为.properties,写入键值对

    package demo;
    
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Properties;
    
    public class PropertiesDemo {
        public static void main(String[] args) throws IOException {
            function();
        }
        
        public static void function() throws IOException{
            Properties pro1 = new Properties();
            FileReader fr1 = new FileReader("d:\pro.properties");
            
            pro1.load(fr1);
            fr1.close();
            System.out.println(pro1);
        }
    }

    store方法:

    写入键值对

    package demo;
    
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Properties;
    
    public class PropertiesDemo {
        public static void main(String[] args) throws IOException {
            function();
        }
        
        public static void function() throws IOException{
            Properties pro1 = new Properties();
            pro1.setProperty("name", "zhangsan");
            pro1.setProperty("age", "18");
            pro1.setProperty("email", "123456@qq.com");
            FileWriter fWriter = new FileWriter("d:\a.properties");
            pro1.store(fWriter, "the reason");//第二个参数经常省略
            fWriter.close();
        }
    }
  • 相关阅读:
    mysql从一张表查出数据存到另一张表和inner join的用法
    pycharm 看函数列表
    git删除本地所有的更改
    mysql create的几种用法和将字段设为插入时间
    python 装饰器
    pycharm退出unittest模式
    股票基础知识
    linux中查找路径下包含某字符串的所有文件
    SQL distinct用法
    SQL update用法
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8301653.html
Copyright © 2011-2022 走看看